[英]draw on image using canvas
I have a picture which which is loaded like this: 我有一张这样加载的图片:
<img src="map/racetrack.jpg" id="map">
And here is my drawing function: 这是我的绘图功能:
this.drawRoute = function(){
var pos = [];
var canvas = $('<canvas/>')[0];
var img = $('#map')[0];
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
$(window).on('mousedown', function(e){
pos.push({
x: e.clientX,
y: e.clientY
});
});
if (positions.length > 1) {
ctx.beginPath();
ctx.moveTo(pos[0].x, pos[0].y);
for (var i = 1; i < pos.length; i++) {
ctx.lineTo(pos[i].x, pos[i].y);
}
ctx.stroke();
}
}
But nothing is drawn on the picture. 但是图片上什么也没画。 I can't see where the mistake is. 我看不出错误在哪里。 I know usually I'm supposed to use <canvas>
element, but I only need this particular part done in canvas, nothing else. 我知道通常我应该使用<canvas>
元素,但是我只需要在画布上完成此特定部分,就别无其他。
Well a few things first you have no canvas element. 好几件事首先您没有画布元素。 Secondly I didnt see where you were calling the draw portion. 其次,我看不到您在哪里叫抽奖部分。
What I ended up doing was adding a canvas element, hiding the image, and then every time you draw it draws the image to the canvas, and then draws the points over it. 我最终要做的是添加一个canvas元素,隐藏该图像,然后在每次绘制时将图像绘制到画布上,然后在其上绘制点。 This should hopefully be enough to get you started. 希望这足以使您入门。
var pos = [];
var canvas = $('#canvas')[0];
var img = $('#map')[0];
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
function render() {
ctx.drawImage(img, 0, 0);
if (pos.length > 1) {
ctx.beginPath();
ctx.moveTo(pos[0].x, pos[0].y);
for (var i = 1; i < pos.length; i++) {
ctx.lineTo(pos[i].x, pos[i].y);
}
ctx.stroke();
}
}
$(window).on('mousedown', function (e) {
pos.push({
x: e.clientX,
y: e.clientY
});
render();
});
render();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.