使用编码64图像构建谷歌地图标记

时间:2012-04-24 22:04:52

标签: javascript google-maps

我有以下功能,它将图像作为参数:

function getIcon(img){
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL;
}

例如:

icon = getIcon(document.getElementById("car_marker"));    

with:

<img id="car_marker" src="img/car.png"/>

然后,创建的图标将用作Google地图中的标记:

var marker = new google.maps.Marker({ position: latLng,
                                          map: map,
                                          title: description,
                                          id: id,
                                          icon: icon
                                       });

这部分工作正常但我现在需要修改getIcon方法,因此它需要另一个图像作为参数并合并两个图像。由于我需要添加的新图像采用base 64编码,因此以下内容无法正常工作:

function getIcon(img1, img2){
  var canvas = document.createElement("canvas");
  canvas.width = img1.width;
  canvas.height = img1.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img1, 0, 0);
  ctx.drawImage(img2, 0, 0); // add the base 64 encoded image here... does not work
  var dataURL = canvas.toDataURL("image/png");
  return dataURL;
}

我最终得到了:

Could not convert JavaScript argument arg 0 [nsIDOMCanvasRenderingContext2D.drawImage]

1 个答案:

答案 0 :(得分:1)

我终于明白了:

// Get the image that will be used as the background image
image1 = document.getElementById("blank_marker");

// Build image from base64 encoding (image that will be put on the previous one)
image2 = new Image();
image2.src = "data:image/jpeg;base64," + base64enc;
image2.height = 20;
image2.width = 20;

然后,拍摄这两张图片的功能:

function getIcon(image1, image2){
  var canvas = document.createElement("canvas");
  canvas.width = image1.width;
  canvas.height = image1.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(image1, 0, 0);
  ctx.drawImage(image2, 1, 1, 28, 28);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL;
}

工作正常(除了一个奇怪的刷新问题:当页面加载时image2没有出现在image1上,但重新加载后它没问题。)