html5 canvas, image as background for arch or circle - javascript

Hello Stackoverflow people, my first post here.
I have a circle on canvas, and circle divided into sky and ground portion, and it is (analog) clock looking, so imagine as hands of the clock were extended to the edge of the circle, making two 'pie slices'. And hands are moving. I would like to have different (background) images for those two portions. Now I have gradiant fill, but I would like to change gradiant with appropriate images. The images must fill their whole portion of 'pie slice'.
My code so far:
// ground portion of circle
var lingrad=ctx.createLinearGradient(center.x, center.y,center.x,main_radius*2);
lingrad.addColorStop(0,'green');
lingrad.addColorStop(1,'brown');
ctx.fillStyle=lingrad;
ctx.beginPath();
ctx.moveTo(center.x, center.y);
ctx.lineTo(x2, y2);
ctx.arc(center.x, center.y, radius, d2r(z1 + 90), d2r(v1 + 90), false);
ctx.moveTo(center.x, center.y);
ctx.lineTo(x1, y1);
ctx.closePath();
ctx.fill();
// sky portion of circle
var lingrad1=ctx.createLinearGradient(center.x,0,center.x,center.y);
lingrad1.addColorStop(0,'yellow');
lingrad1.addColorStop(0.5,'yellow');
lingrad1.addColorStop(1,'cyan');
ctx.fillStyle=lingrad1;
ctx.beginPath();
ctx.moveTo(center.x, center.y);
ctx.lineTo(x2, y2);
ctx.arc(center.x, center.y, radius, d2r(z1 + 90), d2r(v1 + 90), true);
ctx.moveTo(center.x, center.y);
ctx.lineTo(x1, y1);
ctx.closePath();
ctx.fill();
thank you and sorry for my english

You can use for example clip() to do this by first defining the clip path using arc(), call clip(), then draw in the two images in each half.
A simple example:
var img1 = new Image, img2 = new Image, count = 0, ctx = c.getContext("2d");
img1.onload = img2.onload = go;
img1.src = "//i.stack.imgur.com/EU6KB.jpg";
img2.src = "//i.stack.imgur.com/UmEA9.jpg";
function go() {
if (++count < 2) return; // just to make sure both images has loaded
// save state as restoring is the only way to remove a clip-mask
ctx.save();
// define clip-mask using path operations
ctx.arc(75, 75, 75, 0, 6.28);
ctx.clip();
// draw in top image
ctx.drawImage(img1, 0, 0);
// draw in bottom image
ctx.drawImage(img2, 0, 75);
// remove clip mask
ctx.restore();
}
<canvas id=c></canvas>
You can of course use the position, size as well as clipping arguments of drawImage() to taste.

Related

Rotating element on canvas object, relative to parent

I'm trying to draw a pair of skis (two rectangles) on a skier (a square) at varying rotations. I don't quite understand how you line up rotated elements on a canvas as you rotate the whole canvas, not just the object.
At the moment I have this:
ctx.fillStyle = 'rgba(0,0,0,0.8)';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = skiier.color;
ctx.fillRect(skiier.x, skiier.y, skiier.width, skiier.height);
ctx.fillStyle = '#00f';
var angle = 20;
ctx.rotate(angle*Math.PI/180);
ctx.fillRect(skiier.x, skiier.y,100,10);
ctx.fillRect(skiier.x, skiier.y + 20,100,10);
ctx.rotate(-angle*Math.PI/180);
Which gives me this:
But what I'd like to do is the following:
Bearing in mind the x and y coords of the skier is constantly changing, how can I adjust and position the skis relative to him?
I have a demo here if it helps:
http://codepen.io/EightArmsHQ/pen/cfa7052ed205b664b066450910c830c5?editors=001
You should consider the context save, restore and translate as follows:
// ...
var angle = 20;
ctx.save(); // save the state of the ctx
ctx.translate(skiier.x, skiier.y); // translate your context point to be the same as skiier.
ctx.rotate(angle * Math.PI / 180);
ctx.fillRect(-25, 0, 100, 10); // You can draw from new context point.
ctx.fillRect(-25, 20, 100, 10); // Same here.
// Instead of rotating back, use restore()...
// Useful to restore all ctx options as they were before the save()
ctx.restore();
To rotate around a point: you need to translate context to the point, rotate context, translate context back.
For example...
ctx.fillStyle = 'rgba(0,0,0,0.8)';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = skiier.color;
ctx.fillRect(skiier.x, skiier.y, skiier.width, skiier.height);
ctx.fillStyle = '#00f';
var angle = 20;
ctx.translate(skiier.x, skiier.y);
ctx.rotate(angle*Math.PI/180);
ctx.translate(-skiier.x, -skiier.y);
ctx.fillRect(skiier.x, skiier.y,100,10);
ctx.fillRect(skiier.x, skiier.y + 20,100,10);
ctx.rotate(-angle*Math.PI/180);

How to draw and rotate image along with text in HTML5 canvas

I am having a problem with drawing and rotating image on my canvas. Basically, my approach is to create the wheel of fortune which allows customization based on the prizes in form of array. The data in this array makes up the segment inside the wheel based on the number of indexes.
The data is very simple. It is just a simple JSON object like this
var prizes = [
{product:"Axe FX", img: "https://mdn.mozillademos.org/files/5395/backdrop.png"},
{product:"Musicman JPX", img: "https://mdn.mozillademos.org/files/5395/backdrop.png"},
{product:"Ibanez JEM777V", img: "https://mdn.mozillademos.org/files/5395/backdrop.png"}
];
This data is used to create the segments inside the wheel. So I want to place the text which is currently working like a charm for me.
When drawing the wheel, I separate into two main functions. One to draw the wheel and another to draw the segments inside the wheel.
var drawPartial = function(key, lastAngle, angle) {
var value = prizes[key].product;
ctx.save();
ctx.beginPath();
ctx.lineWidth = 6;
ctx.fillStyle = segColors[key];
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, size, lastAngle, angle);
ctx.lineTo(centerX, centerY);
ctx.closePath();
ctx.stroke();
ctx.fill();
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate((lastAngle+angle) / 2);
ctx.fillStyle = "#000";
ctx.fillText(value.substr(0,20), size / 2 + 20, 0);
ctx.restore();
ctx.restore();
}
var draw = function() {
var len = prizes.length;
var currentAngle = outCurrentAngle;
var lastAngle = currentAngle;
ctx.strokeStyle = '#000000';
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.font = "1.4em Arial";
for(var i = 1; i <= len; i++) {
var angle = (Math.PI*2) * (i/len) + currentAngle;
drawPartial(i-1, lastAngle, angle);
lastAngle = angle;
}
ctx.beginPath();
ctx.lineWidth = 2;
ctx.fillStyle = "#fff";
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, size/7, 0, Math.PI*2);
ctx.closePath();
// ctx.stroke();
ctx.fill();
ctx.beginPath();
ctx.lineWidth = 10;
ctx.arc(centerX, centerY, size, 0, Math.PI*2);
ctx.closePath();
// ctx.stroke();
}
With the code above, I just simple call the draw() function and the wheel and all segments will be created accordingly. However, I want to draw the image in each segment but I don't know to make it work. This is the modification of drawPartial() for rendering images along with text
var drawPartial = function(key, lastAngle, angle) {
var value = prizes[key].product;
var img = new Image();
img.src = prizes[key].img;
img.onload = function() {
ctx.save();
ctx.drawImage(img,centerX,centerY);
ctx.save();
ctx.translate(centerX,centerY);
ctx.rotate((lastAngle+angle) / 2);
ctx.drawImage(img,centerX,centerY);
ctx.restore();
ctx.restore();
}
ctx.save();
ctx.beginPath();
ctx.lineWidth = 6;
ctx.fillStyle = segColors[key];
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, size, lastAngle, angle);
ctx.lineTo(centerX, centerY);
ctx.closePath();
ctx.stroke();
ctx.fill();
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate((lastAngle+angle) / 2);
ctx.fillStyle = "#000";
ctx.fillText(value.substr(0,20), size / 2 + 20, 0);
ctx.restore();
ctx.restore();
}
You can see that I add image and its src based on the prizes object which should be called in each iteration called by the main draw() function but it never renders any image in any segment.
What I want is. In each iteration of drawPartial(), I want the image to be placed in the segment along with the text and rotated according to the angle.
Please help...
Problem
In your img.onload function you are "double translating" your centerX & centerY.
ctx.translate(centerX,centerY) will move the canvas's [0,0] origin to [centerX,centerY].
So when you ctx.drawImage(img,centerX,centerY) to draw your image, you are really double moving.
As a result your image is really being drawn at [ centerX*2, centerY*2 ].
A additional thought: Preload your images
It's best to preload all your images. That way if an image fails to load you can take reparative action before you begin drawing your wheel.
Here is how to preload all of your images so they are available when you need to draw them onto your Wheel:
// your incoming JSON
var prizesJSON='[{"product":"Axe FX","img":"https://mdn.mozillademos.org/files/5395/backdrop.png"},{"product":"Musicman JPX","img":"https://mdn.mozillademos.org/files/5395/backdrop.png"},{"product":"Ibanez JEM777V","img":"https://mdn.mozillademos.org/files/5395/backdrop.png"}]';
// the JSON converted to a JS array of objects
var prizes=JSON.parse(prizesJSON);
// preload all images
var imageURLs=[];
var imgs=[];
var imagesOK=0;
// add prize images into the image preloader
for(var i=0;i<prizes.length;i++){
imageURLs.push(prizes[i].img);
}
startLoadingAllImages(imagesAreNowLoaded);
//
function startLoadingAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.src = imageURLs[i];
}
}
//
function imagesAreNowLoaded(){
// add the img objects to your prizes array objects
for(var i=0;i<prizes.length;i++){
prizes[i].imageObject=imgs[i];
// just testing (add the img to the DOM)
document.body.appendChild(imgs[i]);
}
// All images are fully loaded
// So draw your wheel now!
}
body{ background-color: ivory; }
<h4>Testing: (1) Preload all images, (2) Add imgs to DOM</h4>
I had this laying around...
I see you already have code to draw your Wheel, but I had this code in my code archive so I offer it here just in case it has some use for you.
Here is an example of how to draw a "Wheel of Fortune" with each blade containing a prize image and text. The techniques used include:
context.translate to set the rotation point to the center of the wheel.
context.rotate to rotate each blade to its desired angle.
context.textAlign & context.textBaseline to draw centered text.
context.globalAlpha to lighten each blades color so the black text has good contrast.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var PI=Math.PI;
var PI2=PI*2;
var bladeCount=10;
var sweep=PI2/bladeCount;
var cx=cw/2;
var cy=ch/2;
var radius=130;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house32x32transparent.png";
function start(){
for(var i=0;i<bladeCount;i++){
drawBlade(img,'House'+i,cx,cy,radius,sweep*i,sweep);
}
}
function drawBlade(img,text,cx,cy,radius,angle,arcsweep){
// save the context state
ctx.save();
// rotate the canvas to this blade's angle
ctx.translate(cx,cy);
ctx.rotate(angle);
// draw the blade wedge
ctx.lineWidth=1.5;
ctx.beginPath();
ctx.moveTo(0,0);
ctx.arc(0,0,radius,0,arcsweep);
ctx.closePath();
ctx.stroke();
// fill the blade, but keep the color light
// so the black text has good contrast
ctx.fillStyle='white';
ctx.fill();
ctx.fillStyle=randomColor();
ctx.globalAlpha=0.30;
ctx.fill();
ctx.globalAlpha=1.00;
// draw the text
ctx.rotate(PI/2+sweep/2);
ctx.textAlign='center';
ctx.textBaseline='middle';
ctx.fillStyle='black';
ctx.fillText(text,0,-radius+50);
// draw the img
// (resize to 32x32 so be sure orig img is square)
ctx.drawImage(img,-16,-radius+10,32,32);
// restore the context to its original state
ctx.restore();
}
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

Canvas polygons not touching properly

So I've been fiddling with the canvas element, and I seem to have run into a situation that is highly irritating, yet I haven't been able to find a solution.
Say that two polygons are drawn on a canvas, and that they should be touching each other. Where one polygon is drawn like this:
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
A simple version is implemented in this fiddle.
As you can probably see there is a thin line between these shapes. How can I avoid it? I have tried the solutions here, but they don't really seem to refer to this case, because I'm dealing with diagonal lines.
One solution
You could always use the stroke-line trick, but depending on your goal:
If it is to show many polygons next to each other, you could look at the polygons as simple squares.
Draw them in as such in an off-screen canvas next to each other. This will produce a result with no gaps.
Then transform the main canvas into the position you want those polygons to appear. Add rotation and/or skew depending on goal.
Finally, draw the off-screen canvas onto the main canvas as an image. Problem gone.
This will give you an accurate result with no extra steps in stroking, and the calculations for the boxes becomes very simple and fast to do (think 2d grid).
You have to use an off-screen canvas though. If you transform main canvas and draw in the shapes you will encounter the same problem as already present. This is because each point is transformed and if there is need for interpolation it will be calculated for each path shape separately. Drawing in an image will add interpolation on the whole surface, and only where there are gaps (non-opaque alpha). As we already are "gap-free" this is no longer a problem.
This will require an extra step in planning to place them correctly, but this is a simple step.
Example
Step 1 - draw boxes into an off-screen canvas:
This code draws on the off-screen canvas resulting in two boxes with no gap:
(the example uses an on-screen to show result, see next step for usage of off-screen canvas)
var ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 50, 50);
ctx.fillRect(60, 10, 50, 50);
<canvas/>
Step 2 - transform main canvas and draw in off-screen canvas
When drawn into main canvas with transformation set, the result will be (pseudo-random transformation just to show):
var ctx = document.querySelector("canvas").getContext("2d");
// off-screen canvas
var octx = document.createElement("canvas").getContext("2d");
octx.fillStyle = "red";
octx.fillRect(10, 10, 50, 50);
octx.fillRect(60, 10, 50, 50);
// transform and draw to main
ctx.translate(80, 0);
ctx.rotate(0.5, Math.PI);
ctx.transform(1, 0, Math.tan(-0.5),1, 0,0); // skew
ctx.drawImage(octx.canvas, 0, 0);
<canvas />
Step 3 (optional) - Interaction
If you want to interact with the boxes you simply apply the same transform, then add path for a box and hit-test it against the mouse position. Redraw a single state, erase by clearing and draw back the off-screen canvas on top:
var ctx = document.querySelector("canvas").getContext("2d");
// off-screen canvas
var octx = document.createElement("canvas").getContext("2d");
octx.fillStyle = "red";
octx.fillRect(10, 10, 50, 50);
octx.fillRect(60, 10, 50, 50);
// allow us to reuse some of the steps:
function getTransforms() {
ctx.setTransform(1,0,0,1,0,0);
ctx.translate(80, 0);
ctx.rotate(0.5, Math.PI);
ctx.transform(1, 0, Math.tan(-0.5),1, 0,0); // skew
}
function clear() {
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,300,150);
}
function redraw() {
ctx.drawImage(octx.canvas, 0, 0);
}
getTransforms();
redraw();
ctx.canvas.onmousemove = function(e) {
var r = this.getBoundingClientRect(),
x = e.clientX - r.left, y = e.clientY - r.top;
// box 1 (for many, use array)
ctx.beginPath();
ctx.rect(10, 10, 50, 50);
clear(); // these can be optimized to use state-flags
getTransforms(); // so they aren't redraw for every move...
redraw();
// just one box check here
if (ctx.isPointInPath(x, y)) {
ctx.fill();
}
};
<canvas />
Yes, it's annoying when filled polygons result in that tiny gap. It's especially common on diagonals that should theoretically meet.
A common workaround is to put a half-pixel, same-colored stroke around the polygons:
//Some basic setup ...
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var oX = 50;
var oY = 50;
var h = 33;
var k = 50;
ctx.fillStyle = 'red';
ctx.strokeStyle='red';
ctx.lineWidth=0.50;
//Draw one polygon
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
//Draw another polygon
oX = oX+k;
oY = oY+h;
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
//Some basic setup ...
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var oX = 50;
var oY = 50;
var h = 33;
var k = 50;
ctx.fillStyle = 'red';
ctx.strokeStyle='red';
ctx.lineWidth=0.50;
//Draw one polygon
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
//Draw another polygon
oX = oX+k;
oY = oY+h;
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

Canvas animation pixelated

I want to animate an Arc on Canvas, and it works (with a really basic animation, interval), but the outcome is very pixelated/edgy. On the left side I draw an arc (animated), on the right side without animation (smooth).
JsFiddle: http://jsfiddle.net/C8CXz/2/
function degreesToRadians (degrees) {
return degrees * (Math.PI/180);
}
function radiansToDegrees (radians) {
return radians * (180/Math.PI);
}
var canvas = document.getElementById('circle');
var ctx = canvas.getContext('2d');
var start = 0, end = 0;
var int = setInterval(function(){
end++;
ctx.beginPath();
ctx.arc(80, 80, 50, degreesToRadians(0)-Math.PI/2, degreesToRadians(end)-Math.PI/2, false);
ctx.lineWidth = 10;
ctx.stroke();
if(end >= 360) {
clearInterval(int);
}
}, 10);
ctx.beginPath();
ctx.arc(220, 80, 50, degreesToRadians(0)-Math.PI/2, degreesToRadians(360)-Math.PI/2, false);
ctx.lineWidth = 10;
ctx.stroke();
(raw simple code, dont mind the sloppiness)
You need a:
ctx.clearRect(0, 0, w, h);
In each draw loop.
Basically, you are drawing the same arc over itself hundreds of times. The edge pixels that are only partially black are bing darkened over and over until they are completely black.
Things like this are way nearly all canvas animations clear the canvas and draw fresh for each iteration.
Try clearing the drawing rectangle on every frame
ctx.clearRect(x,y,width,height);
http://jsfiddle.net/C8CXz/3/
I found that I first need the clear the canvas.
ctx.clearRect(0, 0, canvas.width, canvas.height);

How do I do a reveal against a black background?

I have an HTML5-based game where I want to reveal the player's character in a certain way.
The end of the James Bond gun barrel sequence is sort of what I'm talking about: http://www.youtube.com/watch?v=YNajzHjjYXQ Around 0:17, there is a circle that reveals the next scene surrounded by a black background. Over the next few seconds, the circle expands to cover the whole screen and then all the black is gone. How can I do this in HTML5 and Javascript?
I would probably do it with canvas and clip a circle before filling. Check the fiddle: http://jsfiddle.net/NgCVA/
As a demonstration, I've placed an image (your game character) on the page and then absolutely positioned a canvas element above it:
<img src="http://zef.me/wp-content/uploads/2009/10/funny-dog-costume.jpg"/>
<canvas width="330" height="396"></canvas>​
Then you'll fill that entire canvas with black repeatedly in an animation loop while clipping a larger and larger circle:
var canvas = document.getElementsByTagName('canvas')[0],
ctx = canvas.getContext('2d'),
cx = canvas.width / 2,
cy = canvas.height / 2,
r = 10,
R_MAX = 400;
ctx.fillstyle = '#000';
function draw() {
r += 1;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
// Draw clipping area
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(canvas.width, 0);
ctx.lineTo(canvas.width, canvas.height);
ctx.lineTo(0, canvas.height);
ctx.closePath();
ctx.moveTo(cx + r, cy);
ctx.arc(cx, cy, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.clip();
// Fill everything not clipped
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
if(r < R_MAX) setTimeout(draw, 10);
}
draw();
Keep in mind that this is very simplistic animation and you'll probably want to do something more elegant (e.g. your own animation loop, easing, whatever). The important part is the technique for clipping and filling on the canvas.

Categories

Resources