简体   繁体   English

在HTML5画布上绘制图像

[英]Draw images on HTML5 canvas

I wanted to draw images on the canvas but the image will only appear at the position when I click on the canvas. 我想在画布上绘制图像,但是图像只会在单击画布时显示在该位置。 I have also learn that element.getBoundingClientRect method which will be able to allow me to get the offsets of the canvas. 我还学习了element.getBoundingClientRect方法,该方法将使我能够获取画布的偏移量。 I wanted to combine them, so when click on any part of the canvas the image will appear at the same location and the X and Y offsets will be display out too. 我想将它们组合起来,所以当单击画布的任何部分时,图像将出现在同一位置,并且X和Y偏移也将显示出来。

Currently my image will be display onload, how do I change it when I Onclick on the canvas the image will the appear at the same position. 当前,我的图像将在加载时显示,当我在画布上单击时如何更改图像,该图像将出现在同一位置。 Second thing is that at the same time the X and Y offsets position of the image will be display out too. 第二件事是,同时将显示图像的X和Y偏移位置。

Modify your JS code like this: 像这样修改您的JS代码:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

$results=$("#results");
$dotposition=$("#dotposition");
var position = {x: 0, y: 0};

function handleMouseMove(e) {
    e.preventDefault();
    e.stopPropagation();

    // You could calc the offsets once if you know
    // the user will not scroll the canvas
    var BB=canvas.getBoundingClientRect();
    var offsetX=BB.left;
    var offsetY=BB.top;

    mouseX=parseInt(e.clientX-offsetX);
    mouseY=parseInt(e.clientY-offsetY);
    $results.text("Mouse position: "+mouseX+" / "+mouseY);
    position.x = mouseX;
    position.y = mouseY;
}

function handleMouseClick(e) {
    //Clearing the canvas before redraw, remove this line if you want to keep prev images
    ctx.clearRect ( 0 , 0 , canvas.width , canvas.height );

    ctx.drawImage(img,position.x - img.width / 2,position.y - img.height / 2);
    $dotposition.text("Dot position: "+position.x+" / "+position.y);
}

var img = new Image();
img.onload = function(){
    canvas.onmousemove = handleMouseMove;
    canvas.onclick = handleMouseClick;
};
img.src="https://dl.dropboxusercontent.com/s/7vlxwy1156wnhcw/redFood.png";

http://jsfiddle.net/ZH4KW/1/ http://jsfiddle.net/ZH4KW/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM