One pixel fill, with canvas - javascript

This might be a somewhat stupid question, but...is it possible to fill an HTML canvas element, pixel by pixel, depending on where a user clicks?
I want to have a blank canvas, that users will click one pixel at a time, which will fill a color, and enter that user/pixel into a database.
How would this be done?
How can I know what pixel, what user clicked?
Thanks

Yes, you can set each canvas pixel individually based on mouse-clicks.
Here's how you set an individual pixel using context.getImageData and context.putImageData:
function setPixel(x, y, red, green, blue) {
pixPos=( (~~x) + (~~y)) * 4;
var pxData = ctx.getImageData(x,y,1,1);
pxData.data[0]=red;
pxData.data[1]=green;
pxData.data[2]=blue;
pxData.data[3]=255;
ctx.putImageData(pxData,x,y);
}
And you get the X/Y position of the mouse click by adding an event listener like this:
// get the position of the canvas relative to the web page
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
// tell the browser to send you mouse down events
// Here I use jquery -- be sure to add jquery or just do addEventListener instead
$("#canvas").mousedown(function(e){handleMouseDown(e);});
// handle the mousedown events that the browser sends you
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
setPixel(mouseX,mouseY,red,green,blue);
}
Here's code and a fiddle: http://jsfiddle.net/m1erickson/wtStf/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var red=255;
var green=0;
var blue=0;
function setPixel(x, y, red, green, blue) {
pixPos=( (~~x) + (~~y)) * 4;
var pxData = ctx.getImageData(x,y,1,1);
pxData.data[0]=red;
pxData.data[1]=green;
pxData.data[2]=blue;
pxData.data[3]=255;
ctx.putImageData(pxData,x,y);
}
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
setPixel(mouseX,mouseY,red,green,blue);
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
[Edited for additional question]
You can easily modify the code to set blocks of pixels like this:
var blockWidth=25;
var blockHeight=25;
function setPixel(x, y, red, green, blue) {
pixPos=( (~~x) + (~~y)) * 4;
var pxData = ctx.getImageData(x,y,blockWidth,blockHeight);
for(var n=0;n<blockWidth*blockHeight;n++){
pxData.data[n*4+0]=red;
pxData.data[n*4+1]=green;
pxData.data[n*4+2]=blue;
pxData.data[n*4+3]=255;
}
ctx.putImageData(pxData,x,y);
}

Related

How to create your own interactive panoramic website

I want to make a website that will be a room, and I want users to be able to look at that room in limited panoramic view, e.g. up/down 30 degrees, left/right 45 degrees, and I want to put objects in that panoramic view that user could interact with.
I have found that google street view could give the panoramic effect, but I'm not quite sure if it would suit my needs as I would want to put objects in it.
Are there any alternative panoramic libraries that are good and could give me tools to support what I want to achieve?
You are basically talking about panning around a view.
You can do that by drawing the view with horizontal & vertical offsets.
Here's annotated code and a Demo: http://jsfiddle.net/m1erickson/32Y5A/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px;}
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.strokeStyle="red";
ctx.lineWidth=5;
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var lastX=0;
var lastY=0;
var panX=0;
var panY=0;
var dragging=[];
var isDown=false;
// create "draggable" rects
var images=[];
images.push({x:200,y:150,width:25,height:25,color:"green"});
images.push({x:80,y:235,width:25,height:25,color:"gold"});
// load the tiger image
var tiger=new Image();
tiger.onload=function(){
draw();
}
tiger.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/tiger.png";
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw tiger
ctx.globalAlpha=0.25;
ctx.drawImage(tiger,panX,panY,tiger.width,tiger.height);
// draw color images
ctx.globalAlpha=1.00;
for(var i=0;i<images.length;i++){
var img=images[i];
ctx.beginPath();
ctx.rect(img.x+panX,img.y+panY,img.width,img.height);
ctx.fillStyle=img.color;
ctx.fill();
ctx.stroke();
}
}
// create an array of any "hit" colored-images
function imagesHitTests(x,y){
// adjust for panning
x-=panX;
y-=panY;
// create var to hold any hits
var hits=[];
// hit-test each image
// add hits to hits[]
for(var i=0;i<images.length;i++){
var img=images[i];
if(x>img.x && x<img.x+img.width && y>img.y && y<img.y+img.height){
hits.push(i);
}
}
return(hits);
}
function handleMouseDown(e){
// get mouse coordinates
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// set the starting drag position
lastX=mouseX;
lastY=mouseY;
// test if we're over any of the images
dragging=imagesHitTests(mouseX,mouseY);
// set the dragging flag
isDown=true;
}
function handleMouseUp(e){
// clear the dragging flag
isDown=false;
}
function handleMouseMove(e){
// if we're not dragging, exit
if(!isDown){return;}
//get mouse coordinates
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// calc how much the mouse has moved since we were last here
var dx=mouseX-lastX;
var dy=mouseY-lastY;
// set the lastXY for next time we're here
lastX=mouseX;
lastY=mouseY;
// handle drags/pans
if(dragging.length>0){
// we're dragging images
// move all affected images by how much the mouse has moved
for(var i=0;i<dragging.length;i++){
img=images[dragging[i]];
img.x+=dx;
img.y+=dy;
}
}else{
// we're panning the tiger
// set the panXY by how much the mouse has moved
panX+=dx;
panY+=dy;
}
draw();
}
// use jQuery to handle mouse events
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag the tiger and<br>independently drag the rectangles.</h4>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Clear Canvas Recursively after translating it

I am trying to translate and save my canvas each time I press right key, so that it moves horizontally each time I press right key. This is the function I am using to move the canvas horizontally each time which is working for the first time and but not later.
function clearRight(){
var canvas1=document.getElementById('plot');
ctx=canvas1.getContext("2d");
ctx.restore();
ctx.translate(-1000,0);
ctx.save();
ctx.clearRect(0,0,canvas1.width,canvas1.height);
}
rightKey(){
clearRight();
draw();
}
Can anyone please point where am I going wrong in trying to move the canvas?
UPDATE
I have solved the issue I was facing.
To move the canvas horizontally
var translated=0;
function clear()
{
var canvas1=document.getElementById('plot');
var ctx=canvas1.getContext("2d");
ctx.restore();
ctx.save();
ctx.clearRect(0,0,canvas1.width,canvas1.height);
}
function rightKey()
{
clear();
ctx.clearRect(0,0,canvas1.width,canvas1.height);
translated += 10;
ctx.translate(-translated,300);
draw(ctx);
}
I'm assuming there's a reason why you're not just drawing an oversized canvas contained in a smaller div-wrapper with scrollbars enabled...so here's an alternative.
You could draw your entire plotted graph to a separate canvas.
Then to pan left/right you can draw that temporary canvas to your main canvas with an offset.
A Demo: http://jsfiddle.net/m1erickson/GfRLq/
Before panning right:
After panning right:
About dynamically changing plots:
If your plots are dynamic, then you can still use this panning technique.
Just update the tempCanvas with each new plot.
Example code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var offset=0;
// create some test data
var points=[];
for(var i=0;i<50;i++){
points.push({x:i*40,y:100+Math.random()*100-50});
}
// create a temporary canvas
var tempCanvas=document.createElement("canvas");
var tempCtx=tempCanvas.getContext("2d");
tempCanvas.width=40*points.length;
tempCanvas.height=300;
// draw your complete plot on the tempCanvas
// draw the line
tempCtx.beginPath();
tempCtx.moveTo(points[0].x,points[0].y);
for(var i=0;i<points.length;i++){
var point=points[i];
tempCtx.lineTo(point.x,point.y);
}
tempCtx.lineWidth=5;
tempCtx.strokeStyle="blue";
tempCtx.stroke();
// draw the markers
for(var i=0;i<points.length;i++){
var point=points[i];
tempCtx.beginPath();
tempCtx.arc(point.x,point.y,10,0,Math.PI*2);
tempCtx.closePath();
tempCtx.fillStyle="black";
tempCtx.fill();
tempCtx.fillStyle="white";
tempCtx.fillText(i,point.x-3,point.y+3);
}
ctx.drawImage(tempCanvas,0,0)
// function to draw the canvas with your specified offset
function drawPlotWithOffset(offset){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(tempCanvas,offset,0,canvas.width,canvas.height,0,0,canvas.width,canvas.height)
}
$("#left").click(function(){
offset-=20;
if(offset<0){offset=0;}
drawPlotWithOffset(offset);
});
$("#right").click(function(){
offset+=20;
if(offset>tempCanvas.width-canvas.width){
offset=tempCanvas.width-canvas.width;
}
drawPlotWithOffset(offset);
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="left">Pan Left</button><br>
<button id="right">Pan Right</button><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

drag image after dropping it in canvas element

To perform drag & drop functionality, with canvas element, I have to actually draw the image in the element of destination using this line,
ctx.drawImage(imgElement,dropX, dropY);
Because it's drawed, I found a difficulty in dragging it again. It's like I can't make it move anymore
I'm working on the basis of this code here : http://jsfiddle.net/m1erickson/cyur7/
What modifications do I have to make, in order to drag again a dropped image?
Keep in mind that canvas is just a bitmap.
Once your images are drawn on the canvas they cannot be repositioned.
To reposition your image, you must clear the canvas and redraw your image in a new position.
To move and redraw your image, you will need to save at least this basic information about the image:
var image1={
x:50,
y:30,
image:imageObject
}
You can let the user drag your image around the canvas by listening to mouse events
In mousedown, check if the mouse is over the image. If yes, start the drag.
In mousemove, add the distance the user dragged since the last mousemove to the images x,y position.
In mouseup, stop the drag.
Here's example code and a Demo: http://jsfiddle.net/m1erickson/L3VjK/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var isDown=false;
var startX;
var startY;
var imgX=50;
var imgY=50;
var imgWidth,imgHeight;
var img=new Image();img.onload=start;img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house32x32transparent.png";
function start(){
imgWidth=img.width;
imgHeight=img.height;
ctx.drawImage(img,imgX,imgY);
}
function handleMouseDown(e){
e.preventDefault();
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
if(startX>=imgX && startX<=imgX+imgWidth && startY>=imgY && startY<=imgY+imgHeight){
isDown=true;
}
}
function handleMouseUp(e){
e.preventDefault();
isDown=false;
}
function handleMouseOut(e){
e.preventDefault();
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
if(!isDown){return;}
imgX+=mouseX-startX;
imgY+=mouseY-startY;
startX=mouseX;
startY=mouseY;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img,imgX,imgY);
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Clipping images into different shapes like triangle, pentagon in html5 canvas?

I am developing a game in html 5 canvas where I have to clip images into many shapes. I also want to join these clipped images using mouse events. Can I only clip a square shape? Also, is it necessary to save x and y co-ordinates of each clipped image to know its position or is there any alternate way?
Here is an example to illustrate how to:
clip an image into 4 triangle pieces,
hit-test the pieces,
move the pieces using your mouse
Here's code and a Fiddle: http://jsfiddle.net/m1erickson/r59ch/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
var isDown=false;
var startX;
var startY;
var parts=[];
var selectedPart=-1;
var img=new Image();
img.onload=function(){
var cx=img.width/2;
var cy=img.height/2;
var w=img.width;
var h=img.height;
parts.push({x:25,y:25,points:[{x:0,y:0},{x:cx,y:cy},{x:0,y:h}]});
parts.push({x:25,y:25,points:[{x:0,y:0},{x:cx,y:cy},{x:w,y:0}]});
parts.push({x:125,y:25,points:[{x:w,y:0},{x:cx,y:cy},{x:w,y:h}]});
parts.push({x:25,y:25,points:[{x:0,y:h},{x:cx,y:cy},{x:w,y:h}]});
drawAll();
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house100x100.png";
function drawAll(){
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<parts.length;i++){
draw(parts[i]);
}
}
function draw(part){
ctx.save();
define(part);
ctx.clip();
ctx.drawImage(img,part.x,part.y);
ctx.stroke();
ctx.restore();
}
function hit(part,x,y){
define(part);
return(ctx.isPointInPath(x,y))
}
function move(part,x,y){
part.x+=x;
part.y+=y;
draw(part);
}
function define(part){
ctx.save();
ctx.translate(part.x,part.y);
ctx.beginPath();
var point=part.points[0];
ctx.moveTo(point.x,point.y);
for(var i=0;i<part.points.length;i++){
var point=part.points[i];
ctx.lineTo(point.x,point.y);
}
ctx.closePath();
ctx.restore();
}
function handleMouseDown(e){
e.preventDefault();
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
for(var i=0;i<parts.length;i++){
if(hit(parts[i],startX,startY)){
isDown=true;
selectedPart=i;
return;
}
}
selectedPart=-1;
}
function handleMouseUp(e){
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseup stuff here
isDown=false;
}
function handleMouseOut(e){
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseOut stuff here
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
e.preventDefault();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
var dx=mouseX-startX;
var dy=mouseY-startY;
startX=mouseX;
startY=mouseY;
//
var part=parts[selectedPart];
move(part,dx,dy);
drawAll();
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag the right triangle-image into place</h4>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
You can define a path and use that for clipping:
ctx.save(); /// store current state of canvas incl. default clip mask
ctx.beginPath();
ctx.moveTo(0, 10);
ctx.lineTo(200, 10);
ctx.lineTo(100, 110);
ctx.clip(); /// will close the path implicit
/// draw graphics here
ctx.restore(); /// restore default infinite clipping mask
This will create a triangle. If you now draw on top the graphics will be clipped to this shape. Coordinates given here are of course just for example.
A small note: the different browsers may or may not anti-alias the clipping mask. If not the result may turn out "hard-edged".
(I recommend to use save()/restore() in connection with clip(). There is suppose to be a resetClip() method but this is rarely implemented in the browsers and is currently considered for removal from the specs.)
An alternative to using clip() is to use image pattern. Define a pattern with the image you want to clip, then create the path as above and use fill() with the pattern set as fillStyle. For this to work properly you need to translate() the canvas before filling to place the image pattern in the desired position.

Drag a canvas element on a circle path

I would like to achieve jQuery Knob-like effect using HTML5 Canvas, but with a circle knob/cursor, instead of the stroke cursor effect that jQuery Knob does.
Based on jQuery Knob code, I was managed to connect the onMouseMove event with my circle knob/cursor so the circle knob moves according to the X and Y coordinates of where the mouse is. However I cannot "restrict" the knob to move only on/along the circle path just like this example, so if I click/mousedown inside the circle path, the circle knob moves to inside the path.
Is there any way to achieve this only using Canavas and jQuery, not Raphael like the example above?
One of my thoughts was to move the circle knob back on track (on the path) whenever mousemove event occurs outside the path (like this). However no luck in succeeding the calculation for this. Is there any math/geometry formula I can use to achieve this?
Just a little bit of trigonometry will answer your question!
This code will find the point on a circle closest to a mouseclick.
var rads = Math.atan2(mouseY - knobCenterY, mouseX - knobCenterX);
var indicatorX=knobRadius*Math.cos(rads)+knobCenterX;
var indicatorY=knobRadius*Math.sin(rads)+knobCenterY;
This code will put an indicator on the knob closest to where the user clicks
And here is a Fiddle --- http://jsfiddle.net/m1erickson/pL5jP/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<!--[if lt IE 9]><script type="text/javascript" src="../excanvas.js"></script><![endif]-->
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var circleArc=Math.PI*2;
// drawing design properties
var knobCenterX=100;
var knobCenterY=100;
var knobRadius=50;
var knobColor="green";
var indicatorRadius=5;
var indicatorColor="yellow";
Draw(canvas.width/2,1); // just to get started
function Draw(mouseX,mouseY){
// given mousePosition, what is the nearest point on the knob
var rads = Math.atan2(mouseY - knobCenterY, mouseX - knobCenterX);
var indicatorX=knobRadius*Math.cos(rads)+knobCenterX;
var indicatorY=knobRadius*Math.sin(rads)+knobCenterY;
// start drawing
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw knob
ctx.beginPath();
ctx.arc(knobCenterX,knobCenterY,knobRadius,0,circleArc,false);
ctx.fillStyle="ivory";
ctx.fill();
ctx.lineWidth=2;
ctx.strokeStyle=knobColor;
ctx.stroke();
// draw indicator
ctx.beginPath();
ctx.arc(indicatorX, indicatorY, indicatorRadius, 0, circleArc, false);
ctx.fillStyle = indicatorColor;
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke();
}
function handleMouseDown(e){
MouseX=parseInt(e.clientX-offsetX);
MouseY=parseInt(e.clientY-offsetY);
Draw(MouseX,MouseY);
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
}); // end $(function(){});
</script>
</head>
<body>
<br/><p>Click anywhere in the canvas to set the knob indicator</p><br/>
<canvas id="canvas" width=200 height=200></canvas>
</body>
</html>

Categories