none
Canvas Pushpin RRS feed

  • Question

  • Hi, I'm trying to insert a pushpin using the HTML5 canvas so that I have an image with a semi-transparent rectangle placed on top, however I can not get the image to appear. It is possible to do this in bing maps v8? This is the code used for the function which creates the icon:

    function CreateIcon() {
        var c = document.createElement('canvas');
        var ctx = c.getContext('2d');
    
        var img = new Image();
        img.onload = function () {
            ctx.drawImage(img, 0, 0);
            //draw a box over the top
            ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
            ctx.fillRect(0, 0, 32, 32);
        };
        img.src = imgsrc;
        return c.toDataURL();
    }

    Thanks

    Friday, July 8, 2016 1:38 PM

Answers

  • This can be achieved, however the issue with your code is that images load asynchronously and as such you are grabbing the data UR of the canvas before the image has loaded. If you want to create your pushpin using a canvas, then you will need to do this asynchronously like this:

    function CreateIcon(imgsrc, callback) {
        var c = document.createElement('canvas');
        var ctx = c.getContext('2d');
    
        var img = new Image();
        img.onload = function () {
            ctx.drawImage(img, 0, 0);
            //draw a box over the top
            ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
            ctx.fillRect(0, 0, 32, 32);
    		
    		callback(c.toDataURL());
        };
        img.src = imgsrc;
    }
    
    function GetMap(){
    	//...Some Map load logic
    	
    	CreateIcon('image url', function(img){
    		var pin = new Microsoft.Maps.Pushpin(map.getCenter(), {
    			icon : img 
    			//You may want to adjust anchor point of pushpin
    			//https://msdn.microsoft.com/en-us/library/mt712695.aspx
    		});
    		
    		map.entities.push(pin);
    	}
    }

    That said, if you need to call this function a lot it likely would be more efficient to use SVG instead of the canvas.

    https://msdn.microsoft.com/en-us/library/mt750262.aspx


    [Blog] [twitter] [LinkedIn]

    Friday, July 8, 2016 4:59 PM