Canvas html5 tutorial pixel rotation
To detect mouseover events for individual pixels with HTML5 Canvas, we can create a custom event handler called handleMouseover() that checks if the mouse coordinates match the coordinates of a drawn pixel.
HTML5 Canvas Pixel Mouseover Example
<!DOCTYPE HTML>
<html>
<head>
<script>
var canvas=null;
var context = null;
var pixelArray = new Array();
function isMouseoverPixel(e, pixel) {
var mouseX = e.clientX - canvas.offsetLeft;
var mouseY = e.clientY - canvas.offsetTop;
if(mouseX == pixel.x &&
mouseY == pixel.y) {
return true;
}
else return false;
}
function Pixel(x,y,color) {
this.x=x;
this.y=y;
this.color=color;
}
function drawPixel(x,y, fillColor) {
context.beginPath();
context.rect(x,y,1,1);
context.fillStyle=fillColor;
context.fill();
pixelArray.push(
new Pixel(x,y, fillColor));
}
window.onload = function() {
canvas=document.getElementById("myCanvas");
context=canvas.getContext("2d");
var colors = new Array();
colors.push("red");
colors.push("orange");
colors.push("yellow");
colors.push("green");
colors.push("blue");
colors.push("purple");
// draw 100px * 100px random pixel square
for (n=0; n<100; n++) {
for (i=0; i<100; i++) {
var colorIndex =
Math.floor(Math.random()*6)
drawPixel(230+n,60+i,colors[colorIndex]);
}
}
drawEventDisplay("Mouseover a pixel...");
}
function drawEventDisplay(eventDisplay) {
context.clearRect(0,0,400,30);
context.font="18pt Calibri";
context.fillStyle="black";
context.fillText(eventDisplay, 10, 25);
}
function handleMouseover(e) {
for (n=0; n<10000; n++) {
var thisPixel = pixelArray[n];
if (isMouseoverPixel(e,
thisPixel)){
var color = thisPixel.color;
drawEventDisplay(color + " pixel!");
}
}
}
</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"
onmousemove="handleMouseover(event)"></canvas>
</body>
</html>
Comments
blog comments powered by Disqus
Recent Posts