!!!以下示例依托 vue 环境!!!
canvas 自适应屏幕宽高
-
canvas
外层套一个div
<div id="map" class="mapDiv">
<canvas id='mapCanvas'>
Your browser does not support the canvas element
</canvas>
</div>
- 在
mounted
函数中进行canvas绘制,并且监听resize
事件
mounted() {
this.resizeCanvas();
window.addEventListener("resize", this.resizeCanvas, false)
},
methods: {
resizeCanvas() {
const canvas = document.getElementById("mapCanvas");
const width = $("#map").width();
const height = $("#map").height();
canvas.width = width;
canvas.height = height;
const cxt = canvas.getContext("2d");
const img = new Image();
img.onload = function() {
cxt.drawImage(img, 0, 0, width, height);
};
img.src = "./images/map.png";
// img.crossOrigin = "";
// img.src = "http://localhost:1024/map.png";
}
}
canvas 获取鼠标点击的点的颜色
- 在
mounted
函数中监听canvas
点击事件
mounted() {
const canvas = document.getElementById("mapCanvas");
canvas.addEventListener("click", this.canvasClick, false);
},
canvasClick(event) {
const canvas = document.getElementById("mapCanvas");
const cxt = canvas.getContext("2d");
// 获取像素点
const color = cxt.getImageData(event.offsetX, event.offsetY, 1, 1).data;
console.log(color);
// 标记点击的点
// cxt.fillStyle = "#FF0000";
// cxt.fillRect(event.offsetX, event.offsetY, 3, 3);
}
代码写完,可能会报错,如下:
Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
解决办法:
1、 修改图片域名为同域
2、为图片服务添加 CROS
(跨域)支持,具体方法是在图片的返回的header中添加 Access-Control-Allow-Origin:*
,同时在请求图片时,为image元素设置 crossOrigin=""
属性设置为空字符串。(img.src
注释的代码)