HTML5 Canvas drawImage resizing issues - javascript

When I resize an image that I pull from a specific location on a spritesheet using drawImage, it appears as if drawImage will sometimes pull outside the source x + source y / swidth + sheight boundaries.
The following jfiddle illustrates what is happening: https://jsfiddle.net/cxuxyLj2/
The pertinent code is as follows:
drawingSurface.drawImage(heroSprite, 0, 64, 32, 64, 20, 144, 32, 64);
drawingSurface.drawImage(heroSprite, 0, 64, 32, 64, 20+50, 144, 32*2, 64*2);
There are lines that show above the RESIZED sprite's head (probably pulling the shoe of the same character on the first row), but not the original sprite's head.
My question is - can it be confirmed that this is a legitimate drawImage error, or am I doing something wrong?

It's actually because of the anti-alias when rescaling your sprite.
Because you do draw in a loop, without ever clearing the context, the anti-alias artifacts becomes bigger and bigger :
var canvas = document.querySelector("canvas");
var drawingSurface = canvas.getContext("2d");
var heroSprite = new Image();
heroSprite.src = "http://gopus.xepher.net/game/gfx/herosprite7.png";
render();
function render () {
setTimeout(render, 1000);
drawingSurface.drawImage(heroSprite, 0, 32, 32, 64, 20, 25, 32, 64);
drawingSurface.drawImage(heroSprite, 0, 32, 32, 64, 20+50, 25, 32*2, 64*2);
drawingSurface.drawImage(heroSprite, 0, 32, 32, 64, 150.6666687774, 25.33333222227, 32,64);
}
<canvas width="400" height="400" style="border:1px solid #000"></canvas>
You could avoid it by setting the imageSmoothingEnabled flag to false but it wasn't supported in IE prior to 10 ...
var canvas = document.querySelector("canvas");
var drawingSurface = canvas.getContext("2d");
drawingSurface.mozImageSmoothingEnabled = false;
drawingSurface.webkitImageSmoothingEnabled = false;
drawingSurface.msImageSmoothingEnabled = false;
drawingSurface.imageSmoothingEnabled = false;
var heroSprite = new Image();
heroSprite.src = "http://gopus.xepher.net/game/gfx/herosprite7.png";
render();
function render() {
setTimeout(render, 16);
drawingSurface.drawImage(heroSprite, 0, 32, 32, 64, 20, 25, 32, 64);
drawingSurface.drawImage(heroSprite, 0, 32, 32, 64, 20 + 50, 25, 32 * 2, 64 * 2);
drawingSurface.drawImage(heroSprite, 0, 32, 32, 64, 150.6666687774, 25.33333222227, 32, 64);
}
<canvas width="400" height="400" style="border:1px solid #000"></canvas>
...or by clearing the canvas at each call, you may avoid the artifacts to grow, but there will still be natural ones...
var canvas = document.querySelector("canvas");
var drawingSurface = canvas.getContext("2d");
var heroSprite = new Image();
heroSprite.src = "http://gopus.xepher.net/game/gfx/herosprite7.png";
render();
function render() {
setTimeout(render, 16);
drawingSurface.clearRect(0,0,canvas.width, canvas.height);
drawingSurface.drawImage(heroSprite, 0, 32, 32, 64, 20, 25, 32, 64);
drawingSurface.drawImage(heroSprite, 0, 32, 32, 64, 20 + 50, 25, 32 * 2, 64 * 2);
drawingSurface.drawImage(heroSprite, 0, 32, 32, 64, 150.6666687774, 25.33333222227, 32, 64);
}
<canvas width="400" height="400" style="border:1px solid #000"></canvas>
... so a final solution would be to use a buffer canvas, to only draw your sprite at normal scale (less anti-aliasing possible), then redraw
this buffer canvas at the wanted scale, you will keep in-image's anti-aliasing artifacts, but won't eat the border's of the cropped area anymore :
var canvas = document.querySelector("canvas");
var drawingSurface = canvas.getContext("2d");
var heroSprite = new Image();
heroSprite.src = "http://gopus.xepher.net/game/gfx/herosprite7.png";
var spriteCanvas = document.createElement('canvas');
var spriteCtx = spriteCanvas.getContext('2d');
var croppedSprite = function(x, y, width, height){
spriteCanvas.width = width;
spriteCanvas.height = height;
spriteCtx.drawImage(heroSprite, x, y, width, height, 0,0, width, height);
return spriteCanvas;
}
render();
function render() {
setTimeout(render, 16);
drawingSurface.drawImage(croppedSprite(0, 64, 32, 64), 20, 25, 32, 64);
drawingSurface.drawImage(croppedSprite(0, 64, 32, 64), 20 + 50, 25, 32 * 2, 64 * 2);
drawingSurface.drawImage(croppedSprite(0, 64, 32, 64), 150.6666687774, 25.33333222227, 32, 64);
}
<canvas width="400" height="400" style="border:1px solid #000"></canvas>
Also, you should definitely add more space between your sprites.

Related

HTML Canvas Not Drawing

I am trying to make a script that will draw squares onto a canvas, but when I run my code the canvas is just white, did I miss something?. Here is my code.
var canvas = document.createElement("canvas")
canvas.id = "canvas"
container.append(canvas);
canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "rgb(242, 144, 7, 1)"
ctx.fillStyle = "rgb(242, 144, 7, 1)"
ctx.rect(0, 0, 50, 50)
There were no errors in the console,
Thanks for your time!
you missed a few lines of code
var container = document.getElementById("container");
var canvas = document.createElement("canvas")
canvas.id = "canvas"
container.append(canvas);
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "rgba(242, 144, 7, 1)"
ctx.fillStyle = "rgba(242, 144, 7, 1)"
ctx.rect(0, 0, 50, 50);
ctx.stroke();
<div id="container">
</div>
You need to use rgba is you are passing 4 values
ctx.strokeStyle = "rgba(242, 144, 7, 1)"
ctx.fillStyle = "rgba(242, 144, 7, 1)"
ctx.rect(0, 0, 50, 50)

Sorting objects on canvas

I draw two bottons using a rectangle with text over top.
As you can see I get two different results using the same loop.
The first "button" has the text hidden behind the box.
The second has the text written on top.
Why is this? How does sorting work in canvas?
<body>
<canvas id="canvas" width="320" height="512"
style="position: absolute; left: 500px; top: 50px; z-index: 1;"></canvas>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext("2d");
canvas.style.backgroundColor = 'rgba(0, 0, 0, 0)';
context.clearRect(0, 0, 320, 16);
gameMenu();
function gameMenu(){
var buttons = [ {x: 210, y: 420, w: 80, h: 30, s: "Messages"},
{x: 210, y: 470, w: 80, h: 30, s: "Pause"} ], i = 0, r;
while(r = buttons[i++]) {
context.rect(r.x, r.y, r.w, r.h);
context.fillStyle = "rgb(26,26,26)";
context.fill();
context.fillStyle = 'White';
context.font = "16px Tahoma";
context.fillText(r.s, r.x + 18, r.y + 22);
}
}
</script>
</body>
Here is a JS Fiddle:
https://jsfiddle.net/oa84Lsxn/1/
You must begin each new path operation (==each new .rect) with context.beginPath. Otherwise all previous .rects will be redrawn along with the current .rect.
Your issue is that all previous paths are redrawn along with the new path. This means your first rect is being redrawn along with your new second rect -- causing the first rect's text to be overwritten by the first rect.
Here's a working version your code with context.beginPath added.
var canvas=document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.style.backgroundColor = 'rgba(0, 0, 0, 0)';
context.clearRect(0, 0, 320, 16);
gameMenu();
function gameMenu(){
// x,y changed to fit demo on StackSnipped window
var buttons = [ {x: 40, y: 20, w: 80, h: 30, s: "Messages"},
{x: 40, y: 70, w: 80, h: 30, s: "Pause"} ],
i = 0, r;
while(r = buttons[i++]) {
context.beginPath();
context.rect(r.x, r.y, r.w, r.h);
context.fillStyle = "rgb(26,26,26)";
context.fill();
context.fillStyle = 'White';
context.font = "16px Tahoma";
context.fillText(r.s, r.x + 18, r.y + 22);
}
}
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

Use canvas drawImage to separate img into two halves

I'm trying to split image in my canvas.
First I'm declaring canvas in HTML:
<canvas width="600" height="400" id="canvas_1">
Canvas tag not supported
</canvas>
Then I'm unsuccesfully spliting my image:
var canvas = document.getElementById("canvas_1");
if (canvas.getContext){
var canvas_context = canvas.getContext("2d");
var img = document.getElementById("london_eye");
canvas_context.drawImage(img, 0, 0, 230, 300, 20, 20, 80, 300);
canvas_context.drawImage(img, 30, 0, 180, 300, 200, 20, 80, 300);
}
I guess I'm missing something there..
canvas_context.drawImage(img, 0, 0, 230, 300, 20, 20, 80, 300);
canvas_context.drawImage(img, 30, 0, 180, 300, 200, 20, 80, 300);
FIDDLE
Thank you for your time and advices
Original Code
var canvas = document.getElementById("canvas_1");
if (canvas.getContext){
var canvas_context = canvas.getContext("2d");
var img = document.getElementById("london_eye");
canvas_context.drawImage(img, 0, 0, 60, 120, 0, 0, 60, 120);
canvas_context.drawImage(img, 60, 0, 60, 120, 70, 0, 60, 120);
}
The last four parameters are destX, destY, destWidth, destHeight. So this is where on the canvas you want to put these pieces, you can see second piece is at 70 so its width of first piece 60 plus gap of 10.
I put a gap of 10px to show the two pieces of your img in the snippet!
var i = new Image();
i.crossOrigin = '';
i.onload = function() {
var canvas = document.getElementById("canvas_1");
if (canvas.getContext){
var canvas_context = canvas.getContext("2d");
canvas_context.drawImage(i, 0, 0, 60, 120, 0, 0, 60, 120);
canvas_context.drawImage(i, 60, 0, 60, 120, 70, 0, 60, 120);
}
};
i.onerror = function() {
i.src = 'http://cors.io?u=' + i.src;
i.onerror = function() {
document.write('Error loading image');
}
};
i.src = 'https://i.stack.imgur.com/olfBw.png';
<canvas id="canvas_1"></canvas>

Change the canvas fillstyle without overlapping with previous color

I'm trying to change fillstyle on focus in and focus out event. When the event call multiple time it's overlapping. Here my code:
function FillColorToFields(id, isOnFocus) {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var coordinates = $('#hidCoord_' + id).val().split(',');
if (isOnFocus) {
context.fillStyle = "rgba(0,255,0,0.1)";
context.fillRect(coordinates[0], coordinates[1], coordinates[2], coordinates[3]);
} else {
context.fillStyle = "rgba(255, 255, 255, 0.5)";
context.fillRect(coordinates[0], coordinates[1], coordinates[2], coordinates[3]);
}
}
Simply use context.clearRect(x, y, width, height). Its purpose is to erase any previously drawn content of the rectangle (check out the documentation). See this forked fiddle for an example.
I set the image as canvas background image instead of drawing it to canvas. It's working fine now.
http://jsfiddle.net/vm47p2sk/8/
<canvas id="myCanvas"></canvas>
<a id = "green" href="#">On focus</a>
<a id = "transparent" href="#">On focus out</a>
$('#myCanvas').css("background-image", "url(https://www.webkit.org/blog-files/acid3-100.png)");
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.strokeStyle = "#009900";
context.lineWidth = 3;
context.strokeRect (5, 5, 100, 100);
$('#green').click(function (){
context.clearRect (8, 8, 94, 94);
context.fillStyle = "rgba(0,255,0,0.1)";
context.fillRect (8, 8, 94, 94);
});
$('#transparent').click(function (){
context.clearRect (8, 8, 94, 94);
context.fillStyle = "rgba(255, 255, 255, 0.1)";
context.fillRect (8, 8, 94, 94);
});

Canvas Bar Graph Animation

I'm trying to get up to speed on the canvas tag and I'm getting stuck when it comes to basic animations. I've searched around and I can get most of the tutorials I've found working, but I've had some trouble translating that into what I'm trying to do.
I have a bar graph that I'm building for my portfolio, and I would like to have the ability to animate the bars on the graph. Basically when the page loads, the bars start from the bottom of the graph, and grow upwards to where they need to be. I have a version I built in jquery found here to give an idea of what I'm after: http://jokedesigns.com/portfoliov6/
Could someone point me in the right direction on how to achieve the animations I'm looking for? Even if its a simple function I should be able to rework it into what I need. Most of the tutorials I've found mainly deal with rotation, I did find one that was a linear animation, but I still wasn't able to quite rework that into what I need.
Here is the code I have so far for the graph:
<html>
<head>
<script type="application/javascript">
function loadImages(sources, callback) {
var images = {};
var loadedImages = 0;
var numImages = 0;
// get num of sources
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
function draw() {
var canvas = document.getElementById("canvas");
var canvasbg = document.getElementById("canvasbg");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var ctx2 = canvasbg.getContext("2d");
var img = new Image();
img.onload = function(){
ctx2.drawImage(img,0,0);
};
img.src = 'skills_bg.jpg';
ctx.fillStyle = "#0a4888";
ctx.fillRect (0, 82, 34, 50);
ctx.fillStyle = "#ed9323";
ctx.fillRect (60, 82, 34, 50);
ctx.fillStyle = "#87982d";
ctx.fillRect (120, 82, 34, 50);
ctx.fillStyle = "#902e63";
ctx.fillRect (180, 82, 34, 50);
ctx.fillStyle = "#262627";
ctx.fillRect (360, 82, 34, 50);
ctx.fillStyle = "#262627";
ctx.fillRect (420, 82, 34, 50);
ctx.fillStyle = "#262627";
ctx.fillRect (480, 82, 34, 50);
ctx.fillStyle = "#262627";
ctx.fillRect (540, 82, 34, 50);
ctx.fillStyle = "#262627";
ctx.fillRect (600, 82, 34, 50);
ctx.fillStyle = "#262627";
ctx.fillRect (660, 82, 34, 50);
ctx.fillStyle = "#262627";
ctx.fillRect (720, 82, 34, 50);
ctx.fillStyle = "#262627";
ctx.fillRect (780, 82, 34, 50);
ctx.fillStyle = "#262627";
ctx.fillRect (840, 82, 34, 50);
var sources = {
ps: 'icn_ps.png',
ai: 'icn_ai.png',
dw: 'icn_dw.png',
id: 'icn_id.png',
ht: 'icn_html.png',
cs: 'icn_css.png',
js: 'icn_js.png',
sql: 'icn_mysql.png',
php: 'icn_php.png',
perl: 'icn_perl.png',
ruby: 'icn_ruby.png',
cplus: 'icn_cplusplus.png',
asp: 'icn_asp.png'
};
loadImages(sources, function(images) {
ctx.drawImage(images.ps, 0, 132, 36, 37);
ctx.drawImage(images.ai, 60, 132, 36, 37);
ctx.drawImage(images.dw, 120, 132, 36, 37);
ctx.drawImage(images.id, 180, 132, 36, 37);
ctx.drawImage(images.ht, 360, 132, 36, 37);
ctx.drawImage(images.cs, 420, 132, 36, 37);
ctx.drawImage(images.js, 480, 132, 36, 37);
ctx.drawImage(images.sql, 540, 132, 36, 37);
ctx.drawImage(images.php, 600, 132, 36, 37);
ctx.drawImage(images.perl, 660, 132, 36, 37);
ctx.drawImage(images.ruby, 720, 132, 36, 37);
ctx.drawImage(images.cplus, 780, 132, 36, 37);
ctx.drawImage(images.asp, 840, 132, 36, 37);
});
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canvasbg" width="960" height="200" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="canvas" width="960" height="200" style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</body>
</html>
You can use requestAnimationFrame to create animation loops to allow your bars to grow
To create uniform growth for bars that are uneven height you can apply a percentage
// this will grow all bars at an even rate
bar1Height = bar1.maxHeight * percentComplete/100;
bar2Height = bar2.maxHeight * percentComplete/100;
percentComplete++;
Here's example code and a Demo: http://jsfiddle.net/m1erickson/YR4D7/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script 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 skillBars=[];
skillBars.push({max:200,color:"red"});
skillBars.push({max:75,color:"green"});
skillBars.push({max:275,color:"blue"});
var chartBottomY=325;
var chartBarWidth=30;
var chartBarPadding=20;
var percent=0;
animate();
function animate() {
// if not 100% done, request another frame
if(percent++<100){
requestAnimationFrame(animate);
}
// Drawing code goes here
ctx.clearRect(0,0,canvas.width,canvas.height);
var x=chartBarPadding;
for(var i=0;i<skillBars.length;i++){
var height=skillBars[i].max*percent/100;
ctx.fillStyle=skillBars[i].color;
ctx.fillRect(x,chartBottomY,chartBarWidth,-height);
x+=chartBarWidth+chartBarPadding;
}
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=350 height=350></canvas>
</body>
</html>
I see a couple issues.
First, you draw everything at one time, whereas you should draw after each image is loaded, but yiu will want to use setTimeout or something similar to allow the canvas element to be drawn.
You should also have a method for the bar, and have it remember the current step value and it will just draw the next block.
I would put onload on the image tag, image.onload function with return, and when it loaded draw the next bar and load the next one.
But remember to use setTimeout to allow the drawing to take place.
Here are some links that may help
JavaScript animation with multiple setTimeout
https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/AnimatingtheCanvas/AnimatingtheCanvas.html

Categories