0

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

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"));    

和:

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

然后创建的图标用作谷歌地图中的标记:

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]
4

1 回答 1

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 上,但重新加载后就可以了)。

于 2012-04-30T06:16:28.367 回答