HTML5 canvas createPattern API - javascript

I have code like:
<body>
<canvas id="main" width=400 height=300></canvas>
<script>
var windowToCanvas = function(canvas, x, y) {
var bbox = canvas.getBoundingClientRect();
return {
x: (x - bbox.left) * (canvas.width / bbox.width),
y: (y - bbox.top) * (canvas.height / bbox.height)
};
};
image = new Image();
image.src = "redball.png";
image.onload = function (e) {
var canvas = document.getElementById('main'),
context = canvas.getContext('2d');
var pattern = context.createPattern(image, "repeat");
function draw(loc) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = pattern;
context.beginPath();
context.moveTo(loc.x, loc.y);
context.lineTo(loc.x + 300, loc.y + 60);
context.lineTo(loc.x + 70, loc.y + 200);
context.closePath();
context.fill();
}
canvas.onmousemove = function(e) {
var event = e || window.event,
x = event.x || event.clientX,
y = event.y || event.clientY,
loc = windowToCanvas(canvas, x, y);
draw(loc);
};
}
</script>
</body>
I call createPattern API, use a background image to fill a Triangle, but when mouse move, the background image also move, I only want the background image at fixed position, how Can I fix this?

Think of a context pattern as a background image on the canvas.
Patterns always begin at the canvas origin [0,0]. If the pattern repeats, then the pattern fills the canvas in tiles repeating rightward and downward.
Therefore, your triangle will always reveal a different portion of the pattern if you move the triangle around the canvas.
There are multiple ways of having your triangle always reveal the same portion of the pattern image.
Option#1 -- context.translate
Move the canvas origin from its default [0,0] position to your triangle position [loc.x,loc.y]. You can do this with canvas transformations. In particular, the translate command will move the origin. Moving the origin will also move the top-left starting position of your pattern so that the pattern always aligns the same way relative to your moving triangle:
var pattern = context.createPattern(image, "repeat");
context.fillStyle=pattern;
function draw(loc) {
context.clearRect(0, 0, canvas.width, canvas.height);
// the origin [0,0] is now [loc.x,loc.y]
context.translate(loc.x,loc.y);
context.beginPath();
// you are already located at [loc.x,loc.y] so
// you don't need to add loc.x & loc.y to
// your drawing coordinates
context.moveTo(0,0);
context.lineTo(300,60);
context.lineTo(70,200);
context.closePath();
context.fill();
// always clean up! Move the origina back to [0,0]
context.translate(-loc.x,-loc.y);
}
A Demo using translate:
var windowToCanvas = function(canvas, x, y) {
var bbox = canvas.getBoundingClientRect();
return {
x: (x - bbox.left) * (canvas.width / bbox.width),
y: (y - bbox.top) * (canvas.height / bbox.height)
};
};
image = new Image();
image.src = "https://dl.dropboxusercontent.com/u/139992952/multple/jellybeans.jpg";
image.onload = function (e) {
var canvas = document.getElementById('main'),
context = canvas.getContext('2d');
var pattern = context.createPattern(image, "repeat");
context.fillStyle=pattern;
draw({x:0,y:0});
function draw(loc) {
context.clearRect(0, 0, canvas.width, canvas.height);
// the origin [0,0] is now [loc.x,loc.y]
context.translate(loc.x,loc.y);
context.beginPath();
// you are already located at [loc.x,loc.y] so
// you don't need to add loc.x & loc.y to
// your drawing coordinates
context.moveTo(0,0);
context.lineTo(300,60);
context.lineTo(70,200);
context.closePath();
context.fill();
// always clean up! Move the origina back to [0,0]
context.translate(-loc.x,-loc.y);
}
canvas.onmousemove = function(e) {
var event = e || window.event,
x = event.x || event.clientX,
y = event.y || event.clientY,
loc = windowToCanvas(canvas, x, y);
draw(loc);
};
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<h4>Move the mouse to move the triangle<br>The image is large, so be patient while it loads</h4>
<canvas id="main" width=600 height=600></canvas>
Option#2 -- compositing
Use compositing instead of patterning to draw an image atop your triangle. Compositing is a method to control how new pixels to be drawn on the canvas will interact with already existing canvas pixels. In particular, source-atop compositing will cause any new pixels to only be drawn where the new pixel overlaps an existing non-transparent pixel. What you would do is draw your triangle in a solid color and then use source-atop compositing to draw your image only where the solid triangle pixels are:
function draw(loc) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(loc.x, loc.y);
context.lineTo(loc.x + 300, loc.y + 60);
context.lineTo(loc.x + 70, loc.y + 200);
context.closePath();
// fill the triangle with a solid color
context.fill();
// set compositing to 'source-atop' so
// new drawings will only be visible if
// they overlap a solid color pixel
context.globalCompositeOperation='source-atop';
context.drawImage(image,loc.x,loc.y);
// always clean up! Set compositing back to its default value
context.globalCompositeOperation='source-over';
}
A Demo using compositing:
var windowToCanvas = function(canvas, x, y) {
var bbox = canvas.getBoundingClientRect();
return {
x: (x - bbox.left) * (canvas.width / bbox.width),
y: (y - bbox.top) * (canvas.height / bbox.height)
};
};
image = new Image();
image.src = "https://dl.dropboxusercontent.com/u/139992952/multple/jellybeans.jpg";
image.onload = function (e) {
var canvas = document.getElementById('main'),
context = canvas.getContext('2d');
var pattern = context.createPattern(image, "repeat");
context.fillStyle=pattern;
draw({x:0,y:0});
function draw(loc) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(loc.x, loc.y);
context.lineTo(loc.x + 300, loc.y + 60);
context.lineTo(loc.x + 70, loc.y + 200);
context.closePath();
// fill the triangle with a solid color
context.fill();
// set compositing to 'source-atop' so
// new drawings will only be visible if
// they overlap a solid color pixel
context.globalCompositeOperation='source-atop';
context.drawImage(image,loc.x,loc.y);
// always clean up! Set compositing back to its default value
context.globalCompositeOperation='source-over';
}
canvas.onmousemove = function(e) {
var event = e || window.event,
x = event.x || event.clientX,
y = event.y || event.clientY,
loc = windowToCanvas(canvas, x, y);
draw(loc);
};
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<h4>Move the mouse to move the triangle<br>The image is large, so be patient while it loads</h4>
<canvas id="main" width=600 height=600></canvas>
More Options...
There are more possible options, too. I'll mention some of them without giving code examples:
Create an img element of your filled triangle and use drawImage(img,loc.x,loc.y) to move that triangle-image around the canvas
Create a clipping region from your triangle. Clipping regions cause new drawings to only be displayed in the defined clipping region. In this case, the new drawImage would only be visible inside your triangle shape and would not be visible outside your triangle.
And more options that are less conventional...

Related

Rotate canvas image to anticlockwise in the same canvas

Say we have a canvas:
<canvas id="one" width="100" height="200"></canvas>
var canvas = document.getElementById("one");
var context = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
// Sample graphic
context.beginPath();
context.rect(10, 10, 20, 50);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
// create button
var button = document.getElementById("rotate");
button.onclick = function () {
// rotate the canvas 90 degrees each time the button is pressed
rotate();
}
var myImageData, rotating = false;
var rotate = function () {
if (!rotating) {
rotating = true;
// store current data to an image
myImageData = new Image();
myImageData.src = canvas.toDataURL();
myImageData.onload = function () {
// reset the canvas with new dimensions
canvas.width = ch;
canvas.height = cw;
cw = canvas.width;
ch = canvas.height;
context.save();
// translate and rotate
context.translate(cw, ch / cw);
context.rotate(Math.PI / 2);
// draw the previows image, now rotated
context.drawImage(myImageData, 0, 0);
context.restore();
// clear the temporary image
myImageData = null;
rotating = false;
}
}
}
And on a button click the canvas gets rotated -90 degrees anticlockwise (around the centre) and the dimensions of the canvas get also updated, so in a sense, it looks like this afterwards:
I want to rotate a canvas element to the anticlockwise rotation. I have used this code but it's not working as I want.
JavaScript has a built-in rotate() function for canvas context:
context.rotate( angle * Math.PI / 180);
The problem is that the rotation will only affect drawings made AFTER the rotation is done, which means you will need to:
Clear the canvas first: context.clearRect(0, 0, canvas.width, canvas.height);
Rotate the context context.rotate( 270 * Math.PI / 180);
Redraw the graphics
Thus, I recommend wrapping the graphics we want to draw in a function to make it easier to call after every rotation:
function drawGraphics() {
context.beginPath();
context.rect(10, 10, 20, 50);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
}

rotate one of the 2 canvas objects placed in canvas

I'm developing web app using canvas and I made three. canvas, canvas_panorama and canvas_image.
First one is something like main canvas, conteiner for the others. canvas_panorama is a background for canvas_image.
After canvas is right clicked, I'm computing angle to rotate canvas_image:
function getAngle( e, pw /*canvas*/ ){
var offset = pw.offset();
var center_x = (offset.left) + ($(pw).width() / 2);
var center_y = (offset.top) + ($(pw).height() / 2);
var mouse_x = e.pageX;
var mouse_y = e.pageY;
var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
angle = radians;
}
After I have an angle I'm trying to rotate canvas_image like this:
function redraw(){
var p1 = ctx.transformedPoint(0,0);
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
ctx.clearRect( p1.x, p1.y, p2.x-p1.x, p2.y-p1.y );
canvas_image_ctx.drawImage(image_img, 0, 0, 150, 150);
canvas_panorama_ctx.drawImage(panorama_img, 0, 0, 600, 300);
canvas_panorama_ctx.drawImage(canvas_image, 20, 20);
// rotate panorama_img around its center
// x = x + 0.5 * width
// y = y + 0.5 * height
canvas_panorama_ctx.translate(95, 95);
canvas_panorama_ctx.rotate(angle);
// translate to back
canvas_panorama_ctx.translate(-95, -95);
ctx.drawImage(canvas_panorama, 0, 0);
}
But this rotates both canvas_image and canvas_panorama. It should only rotate canvas_image
JSFiddle to show you my problem
I think you are confusing yourself with this idea of multiple canvases.
Once in the drawImage() method, every of your canvases are just images, and could be just one or even just plain shapes.
Transformation methods do apply to the canvas' context's matrix, and will have effect only if you do some drawing operations when they are set.
Note : To reset your context matrix, you can either use save(); and restore() methods which will also save all other properties of your context, so if you only need to reset the transform, then it's preferred to simply reset the transformation matrix to its default : ctx.setTransform(1,0,0,1,0,0).
Here is a simplified example to make things clearer :
var ctx = canvas.getContext('2d');
// a single shape, with the border of the context matrix
var drawRect = function(){
ctx.beginPath();
ctx.rect(10, 10, 50, 20);
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.stroke();
};
// set the color of our shapes
var gradient = ctx.createLinearGradient(0,0,70,0);
gradient.addColorStop(0,"green");
gradient.addColorStop(1,"yellow");
ctx.fillStyle = gradient;
// here comes the actual drawings
//we don't have modified the transform matrix yet
ctx.strokeStyle = "green";
drawRect();
// here we translate of 100px then we do rotate the context of 45deg
ctx.translate(100, 0)
ctx.rotate(Math.PI/4)
ctx.strokeStyle = "red";
drawRect();
// reset the matrix
ctx.setTransform(1,0,0,1,0,0);
// here we move of 150px to the right and 25px to the bottom
ctx.translate(150, 25)
ctx.strokeStyle = "blue";
drawRect();
// reset the matrix
ctx.setTransform(1,0,0,1,0,0);
<canvas id="canvas" width="500" height="200"></canvas>
In your code, you are setting the transformations on the canvas that does represent your image, and you do draw every of your canvases at each call.
What you want instead, is to set the transformation on the main canvas only, and draw the non-transformed image :
var main_ctx = canvas.getContext('2d');
var img_canvas = canvas.cloneNode();
var bg_canvas = canvas.cloneNode();
var angle = 0;
// draw on the main canvas, and only on the main canvas
var drawToMain = function(){
// first clear the canvas
main_ctx.clearRect(0,0,canvas.width, canvas.height);
// draw the background image
main_ctx.drawImage(bg_canvas, 0,0);
// do the transforms
main_ctx.translate(img_canvas.width/2, img_canvas.height/2);
main_ctx.rotate(angle);
main_ctx.translate(-img_canvas.width/2, -img_canvas.height/2);
// draw the img with the transforms applied
main_ctx.drawImage(img_canvas, 0,0);
// reset the transforms
main_ctx.setTransform(1,0,0,1,0,0);
};
// I changed the event to a simple onclick
canvas.onclick = function(e){
e.preventDefault();
angle+=Math.PI/8;
drawToMain();
}
// a dirty image loader
var init = function(){
var img = (this.src.indexOf('lena')>0);
var this_canvas = img ? img_canvas : bg_canvas;
this_canvas.width = this.width;
this_canvas.height = this.height;
this_canvas.getContext('2d').drawImage(this, 0,0);
if(!--toLoad){
drawToMain();
}
};
var toLoad = 2;
var img = new Image();
img.onload = init;
img.src = "http://pgmagick.readthedocs.org/en/latest/_images/lena_scale.jpg";
var bg = new Image();
bg.onload = init;
bg.src = 'http://www.fnordware.com/superpng/pnggradHDrgba.png';
<canvas id="canvas" width="500" height="300"></canvas>

How to drag shapes (like rect,circle,other polygons,etc) around the canvas using native javascript

Am simulating a shape click and trying to do drag/drop inside canvas using Sahi framework.I have found some references that by looping through an array containing that shapes position/sizes , we get whether shape is clicked.While testing other website using sahi framework/native jaascript , how can it be achieved ? I wanted to select that shape inside canvas and do drag and drop inside canvas.This is my goal.
In html5 canvas, A "Shape" is defined and drawn using a Path.
You define a shape by:
Declaring that you a beginning a new path: context.beginPath
Using one or more of the path definition commands: moveTo, lineTo, arc, etc.
// define a triangle path
context.beginPath();
context.moveTo(x+50,y+50);
context.lineTo(x+100,y+100);
context.lineTo(x+0,y+100);
// see not below about .closePath()
context.closePath();
Note: context.closePath is NOT used to close a context.beginPath command -- it is NOT like a closing parenthesis! Instead, it is used to draw a line from the last coordinate to the starting coordinate -- to "enclose" the path. In our example, it draws an "enclosing" line from [x+0,y+100] to [x+50,y+50].
Just defining a path will not cause it to be drawn onto the canvas. To actually draw the shape onto the canvas you can:
Stroke the outline of the path, and / or
Fill the inside of the path.
context.stroke();
context.fill();
For example, here's how to define and draw a triangle. You can also use offset variables ([x,y] in the example) to reposition the triangle anywhere on the canvas.
// set the offset of the triangle
var x=30;
var y=40;
// define the path
context.beginPath();
context.moveTo(x+50,y+50);
context.lineTo(x+100,y+100);
context.lineTo(x+0,y+100);
context.closePath();
// stroke the path
context.stroke();
// if desired, you can also fill the inside of the path
context.fill();
To drag a shape, you must test whether the mouse is over that shape. You can "hit-test" the most recently defined shape using context.isPointInPath.
Be sure you read that carefully!
You can hit-test the most recently "defined" path. If you define and draw multiple paths then isPointInPath will only hit-test the last defined path.
if(context.isPointInPath(mouseX,mouseY)){
console.log('Yes, the mouse is in the triangle.');
}
Also note that you don't have to re-stroke the path being tested so your drawings won't be altered by the hit-testing process. So you hit-test multiple paths by:
Define one of the paths
Hit test with isPointInPath(mouseX,mouseY)
Repeat step#1 for the next path (path==shape)
Nothing drawn to the canvas can be moved -- everything is as permanent as dried paint. So to "move" a shape on canvas you clear the entire canvas and redraw the shape in its moved position:
// clear the canvas
context.clearRect(canvas.width,canvas.height);
// move the canvas by changing it's offsets
x+=20;
y+=30;
// redefine and restroke the shape
context.beginPath();
context.moveTo(x+50,y+50);
context.lineTo(x+100,y+100);
context.lineTo(x+0,y+100);
context.closePath();
context.stroke();
To make redefining and re-stroking the shape more reusable you can put the code in a function:
function myTriangle(alsoStroke){
context.beginPath();
context.moveTo(x+50,y+50);
context.lineTo(x+100,y+100);
context.lineTo(x+0,y+100);
context.closePath();
if(alsoStroke){
context.stroke();
}
}
You can read more about dragging a shape in this previous post. Since you can't move a shape you can't "drag" a shape either. You must again clear the canvas and redraw it in its newly dragged position.
To drag a shape you need to listen to 4 mouse events.
In mousedown: Check if the mouse is over the shape, and, if yes, set a flag indicating a drag has begun. To check if the mouse is over the shape, you can use canvas context's isPointInPath method which tests if an [x,y] point is inside the most recently drawn path.
In mousemove: If the dragging flag is set (indicating a drag is in process), change the position of the selected text by the distance the user has dragged and redraw the shape in its new position
In mouseup or in mouseout: The drag is over so clear the dragging flag.
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var isDown=false;
var startX,startY;
var poly={
x:0,
y:0,
points:[{x:50,y:50},{x:75,y:25},{x:100,y:50},{x:75,y:125},{x:50,y:50}],
}
ctx.fillStyle='skyblue';
ctx.strokeStyle='gray';
ctx.lineWidth=3;
draw();
// listen to mouse events
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
function draw(){
ctx.clearRect(0,0,cw,ch);
define();
ctx.fill();
ctx.stroke()
}
function define(){
ctx.beginPath();
ctx.moveTo(poly.points[0].x+poly.x,poly.points[0].y+poly.y);
for(var i=0;i<poly.points.length;i++){
ctx.lineTo(poly.points[i].x+poly.x,poly.points[i].y+poly.y);
}
ctx.closePath();
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
define();
if(ctx.isPointInPath(startX,startY)){
isDown=true;
}
}
function handleMouseUp(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseup stuff here
isDown=false;
}
function handleMouseOut(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mouseOut stuff here
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
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;
poly.x+=dx;
poly.y+=dy;
draw();
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Drag the polygon</h4>
<canvas id="canvas" width=300 height=300></canvas>
[ Addition: Discovering Rectangles using context.getImageData ]
If you don't have the shape's position/size and you instead have an image of a shape then you must get the position/size by searching the pixels. Here's an example showing how to isolate rectangles by searching pixels:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw, ch;
// background definition
// OPTION: look at the top-left pixel and assume == background
// then set these vars automatically
var isTransparent = false;
var bkColor = {
r: 255,
g: 255,
b: 255
};
var bkFillColor = "rgb(" + bkColor.r + "," + bkColor.g + "," + bkColor.b + ")";
cw = canvas.width;
ch = canvas.height;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawTestRect(30, 30, 50, 50, "1");
drawTestRect(100, 30, 50, 30, "2");
drawTestRect(170, 30, 30, 50, "3");
function drawTestRect(x, y, w, h, label) {
ctx.fillStyle = "black";
ctx.fillRect(x, y, w, h);
ctx.fillStyle = "white";
ctx.font = "24px verdana";
ctx.fillText(label, x + 10, y + 25);
}
function clipBox(data) {
var pos = findEdge(data);
if (!pos.valid) {
return;
}
var bb = findBoundary(pos, data);
alert("Found target at "+bb.x+"/"+bb.y+", size: "+bb.width+"/"+bb.height);
clipToImage(bb.x, bb.y, bb.width, bb.height);
if (isTransparent) {
// clear the clipped area
// plus a few pixels to clear any anti-aliasing
ctx.clearRect(bb.x - 2, bb.y - 2, bb.width + 4, bb.height + 4);
} else {
// fill the clipped area with the bkColor
// plus a few pixels to clear any anti-aliasing
ctx.fillStyle = bkFillColor;
ctx.fillRect(bb.x - 2, bb.y - 2, bb.width + 4, bb.height + 4);
}
}
function xyIsInImage(data, x, y) {
// find the starting index of the r,g,b,a of pixel x,y
var start = (y * cw + x) * 4;
if (isTransparent) {
return (data[start + 3] > 25);
} else {
var r = data[start + 0];
var g = data[start + 1];
var b = data[start + 2];
var a = data[start + 3]; // pixel alpha (opacity)
var deltaR = Math.abs(bkColor.r - r);
var deltaG = Math.abs(bkColor.g - g);
var deltaB = Math.abs(bkColor.b - b);
return (!(deltaR < 5 && deltaG < 5 && deltaB < 5 && a > 25));
}
}
function findEdge(data) {
for (var y = 0; y < ch; y++) {
for (var x = 0; x < cw; x++) {
if (xyIsInImage(data, x, y)) {
return ({
x: x,
y: y,
valid: true
});
}
}
}
return ({
x: -100,
y: -100,
valid: false
});
}
function findBoundary(pos, data) {
var x0 = x1 = pos.x;
var y0 = y1 = pos.y;
while (y1 <= ch && xyIsInImage(data, x1, y1)) {
y1++;
}
var x2 = x1;
var y2 = y1 - 1;
while (x2 <= cw && xyIsInImage(data, x2, y2)) {
x2++;
}
return ({
x: x0,
y: y0,
width: x2 - x0,
height: y2 - y0 + 1
});
}
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = "red";
ctx.lineWidth = 0.50;
ctx.stroke();
}
function clipToImage(x, y, w, h) {
// don't save anti-alias slivers
if (w < 3 || h < 3) {
return;
}
// save clipped area to an img element
var tempCanvas = document.createElement("canvas");
var tempCtx = tempCanvas.getContext("2d");
tempCanvas.width = w;
tempCanvas.height = h;
tempCtx.drawImage(canvas, x, y, w, h, 0, 0, w, h);
var image = new Image();
image.width = w;
image.height = h;
image.src = tempCanvas.toDataURL();
$("#clips").append(image);
}
$("#unbox").click(function () {
var imgData = ctx.getImageData(0, 0, cw, ch);
var data = imgData.data;
clipBox(data);
});
body {
background-color: ivory;
}
canvas {
border:1px solid red;
}
#clips {
border:1px solid blue;
padding:5px;
}
img {
margin:3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="unbox">Clip next sub-image</button><br>
<canvas id="canvas" width=300 height=150></canvas><br>
<h4>Below are images clipped from the canvas above.</h4><br>
<div id="clips"></div>
[Addition: discovering the bounds of a reddishness stroked rectangle]
You can test for "reddishness" by checking if the red component value of a pixel is much larger than the green & blue component values.
function xyIsInImage(data, x, y) {
// find the starting index of the r,g,b,a of pixel x,y
var n = (y * cw + x) * 4;
return(data[n+3]>240 && // this pixel is mostly opaque
data[n]-data[n+1]>180 && // this pixel is more reddish than green
data[n]-data[n+2]>180 // this pixel is more reddish then blue
);
Then use this reddishness test to find the bounds of the reddish stroked rectangle:
Find the theoretical top-left pixel of the red rect. The discovered pixel is probably on the top of the rect. It might not be on the left of the rect because your image shows the rect's corner pixels are much less reddish. So declare the y value as the top of the rect.
Move towards the center of the rect by a few pixels.
Test each vertical pixel downward until you find the bottom reddish border of the stroked rect.
Test each horizontal pixel rightward until you find the right reddish border of the stroked rect.
Test each horizontal pixel leftward until you find the left reddish border of the stroked rect.
Now you have found the top-left and bottom-right bounds of the rect.
Here's example code and a demo using your image:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/raw.png";
function start(){
cw=canvas.width=img.width;
ch=canvas.height=img.height;
ctx.drawImage(img,0,0);
var data=ctx.getImageData(0,0,cw,ch).data;
var edge=findEdge(data);
var top=edge.y;
var x,y,left,bottom,right;
var off=25;
for(var y=edge.y+off;y<ch;y++){if(xyIsInImage(data,edge.x+off,y)){bottom=y; break;}}
for(var x=edge.x+off;x<cw;x++){if(xyIsInImage(data,x,edge.y+off)){right=x;break;}}
for(var x=edge.x+off;x>=0;x--){if(xyIsInImage(data,x,edge.y+off)){left=x;break;}}
dot({x:left,y:top});
dot({x:right,y:bottom});
}
//
function dot(pt){
ctx.beginPath();
ctx.arc(pt.x,pt.y,4,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle='red';
ctx.fill();
ctx.strokeStyle='gold';
ctx.lineWidth=2;
ctx.stroke();
}
function xyIsInImage(data, x, y) {
// find the starting index of the r,g,b,a of pixel x,y
var n = (y * cw + x) * 4;
return(data[n+3]>240 &&
data[n]-data[n+1]>180 &&
data[n]-data[n+2]>180
);
}
function findEdge(data) {
for (var y = 0; y < ch; y++) {
for (var x = 0; x < cw; x++) {
if(xyIsInImage(data, x, y)){ return ({x:x,y:y,valid:true}); }
}
}
return ({x:-100,y:-100,valid:false});
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<h4>Red-gold dots are on top-left & bottom-right of target rect.</h4>
<canvas id="canvas" width=300 height=300></canvas>

Crop image like pie chart

I want to crop image over another image like a pie-chart to create a loading animation. I was thinking of using raphaeljs, but couldn't find any information about image cropping in pie-chart style.
Here are the sample images:
Start state:
End state:
What it should look like:
Just draw a semi-transparent filled arc on top of the image (adjust alpha value to your pleasing):
var ctx = document.querySelector("canvas").getContext("2d"),
img = new Image;
img.onload = draw;
img.src = "http://i.imgur.com/hQ5Pljv.png";
function draw(){
var cx = 157, cy = 159, r = 150,
pst = 0,
ang = Math.PI * 2 * (pst/100),
dlt = 2;
// animate the following part
(function loop() {
ctx.drawImage(img, 0, 0);
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, r, 0, ang);
ctx.fillStyle = "rgba(0,0,0,0.33)"; // adjust alpha here
ctx.fill();
pst += dlt;
if (pst <= 0 || pst >= 100) dlt = -dlt;
ang = Math.PI * 2 * (pst/100);
requestAnimationFrame(loop)
})()
}
<canvas width=320 height=320></canvas>
Method two - compositing
Use two steps to clip the same arc above to use images instead:
Draw arc, this will be the composite data
Change comp. mode to source-atop - next drawing replaces the drawn arc
Draw secondary image in
Change comp. mode to destination-atop - next drawing will fill all non-pixels
Draw main image in
Demo:
var ctx = document.querySelector("canvas").getContext("2d"),
img1 = new Image, img2 = new Image, cnt=2;
img1.onload = img2.onload = loader;
img1.src = "http://i.imgur.com/hQ5Pljv.png";
img2.src = "http://i.imgur.com/k70j3qp.jpg";
function loader(){if (!--cnt) draw()};
function draw(){
var cx = 157, cy = 159, r = 150,
pst = 0, ang = Math.PI * 2 * (pst/100), dlt = 2;
// animate the following part
(function loop() {
ctx.clearRect(0, 0, 320, 320); // clear canvas, or set last comp mode to "copy"
// first arc
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, r, 0, ang);
ctx.fill(); // this will be comp. basis for the next steps
// comp mode secondary image
ctx.globalCompositeOperation = "source-atop"; // replaces filled arc
ctx.drawImage(img2, 0, 0);
// comp mode main image
ctx.globalCompositeOperation = "destination-atop"; // fills all non-pixels
ctx.drawImage(img1, 0, 0);
pst += dlt; if (pst <= 0 || pst >= 100) dlt = -dlt; ang = Math.PI * 2 * (pst/100);
ctx.globalCompositeOperation = "source-over"; // reset comp. mode
requestAnimationFrame(loop)
})()
}
<canvas width=320 height=320></canvas>
You'll want an algorithm along the lines of:
Draw image A onto canvas 1
Clear canvas 2
Draw a partial circle on canvas 2, for the current state of the spinner, filled with white
Blit image B onto canvas 2, using the multiplicative blending mode
Blit canvas 2 onto canvas 1, using standard (replace) blending
Canvas 2 should contain the second image, masked by the section you want to use. Overlaying that onto canvas 1, provided you handle transparency properly, should give the effect you want.
You can also use two SVG circles with image backgrounds and do this trivially, assuming your target browsers support SVG.

Drag Move an Image inside a Circle (circular movement)

I drawn a circle in canvas and put an image near the border. Now I have absolutely no idea..I want to drag the image around the circle but the top of the arrow image should always be on the border.
For Example: I drag the arrow from the top to the left at nine o'clock. Now the arrow image needs to be rotated 90 degrees.
http://jsfiddle.net/L5twk3ak/1/
canvas = document.getElementById('test');
var context = canvas.getContext("2d");
var points = [];
var radius = 55;
imageBG = new Image();
imageBG.onload = function() {context.drawImage(imageBG, 148, 100, 15, 15);};
imageBG.src = 'https://www.nanamee.com/upload/images/5945/5945_p.jpg';
for(var degree = 0; degree < 360; degree++)
{
var radians = degree * Math.PI / 179;
var x = 150 + radius * Math.cos(radians);
var y = 150 + radius * Math.sin(radians);
points.push({x : x, y : y});
}
context.beginPath();
context.moveTo(points[0].x + 4, points[0].y + 4)
for(var i = 1; i < points.length; i++)
{
var pt = points[i];
context.lineTo(pt.x + 4, pt.y + 4);
}
context.strokeStyle = "black";
context.lineWidth = 1;
context.stroke();
context.closePath();
<canvas id="test" width="400" height="400">Your browser does not support the HTML5 canvas tag.</canvas>
You need to :
Draw your Arc as we're supposed to (unless you have better plans with lineTo() )
calculate the mouse position inside the canvas - on mousemove.
calculate the resultant degree depending on Mouse Position vs. the Arc center.
cache your image for reuse
create draw functions (one for the Arc, the other for drawing the Image after translating the canvas context). That way on (click+drag) mousemove you can simply reuse them to draw your objects into Canvas.
I'll not show you how to implement the click+drag cause it's pretty trivial: you simply need to apply your draw functions if both CLICK+MOUSEMOVE are registered.
Here's the interesting calculations part:
var canvas = document.getElementById('test'); // Store in variable!
var context = canvas.getContext("2d");
var circle = {rad: 55, x:100, y:100}; // Object for ease of use
var img = {src:'//placehold.it/13x13/000', x:0 ,y:0, w:13, h:13};
var arrowImg; // Store for later Image reference
function drawArc(){
context.beginPath();
context.arc(circle.x, circle.y, circle.rad, 0, Math.PI*2, true);
context.strokeStyle = "#000";
context.lineWidth = 1;
context.stroke();
context.closePath();
}
function drawImg( deg ){
context.save(); // save before we mess with ctx translations
context.translate(circle.y, circle.x); // temporarily translate the ctx
// to the Arc center coordinates.
context.rotate(deg*Math.PI/180); // we need Radians so deg*Math.PI/180
context.drawImage(arrowImg, circle.rad-img.w, -img.h/2);
context.restore(); // restore to default
}
function calcDeg(e){ // Retrieve degree from mouse position vs. arc center
var mPos = {
x : e.pageX-canvas.offsetLeft-circle.x,
y : e.pageY-canvas.offsetTop-circle.y
};
var getAtan = Math.atan2(mPos.y, mPos.x);
return getAtan*180/Math.PI;
}
drawArc(); // Draw the ARc
arrowImg = new Image(); // Create Image Obj
arrowImg.onload = function(){ drawImg(-90) }; // onload draw the Image
arrowImg.src = img.src;
canvas.addEventListener("mousemove", function(evt){
canvas.width = canvas.width; // clear the canvas
drawArc(); // Draw Arc
drawImg( calcDeg(evt) ); // Draw Image at the calculated degree
}, false);
canvas{background:#eee;}
<canvas id="test" width="400" height="400">Your browser does not support the HTML5 canvas tag.</canvas>
Not clear? Goog, than ask

Categories