No subpixel positioning on small HTML5 canvas on chrome - html

When animating an image over a large canvas, the image renders correctly on non-integer coordinates, and the animation is smooth.
on a small canvas, say 200x200, the subpixel coordinates don't apply, and the image "jumps" from integer location to the next, creating a "jittery" motion.
the issue seems to apply to raster sources only (images and canvases). text, for instance, animates smoothly on all canvas sizes.
i'm currently testing with Chrome Version 58.0.3029.110 (64-bit), however the issue appeared on earlier versions as well.
has anyone stumbled upon this issue?
here's the code i test with:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<script>
var outer = [200, 200];
var inner = [200, 200];
function CreateCanvas(w, h, hidden) {
var canvas = document.createElement('canvas');
if(!hidden) document.body.appendChild(canvas);
canvas.width = w;
canvas.height = h;
var context = canvas.getContext('2d');
return {canvas:canvas, context:context};
}
function rgba2hex(color) {
return "rgba(" + Math.floor(color[0] * 255) + ',' + Math.floor(color[1] * 255) + ',' + Math.floor(color[2] * 255) + ',' + color[3] + ")";
}
function GetSystemTimeMS() {
return (new Date()).getTime();
}
function GetTimeDifferenceMS(time) {
return GetSystemTimeMS() - time;
}
var outerFontSize = Math.min(100, outer[1] * 0.3);
var innerFontSize = Math.min(100, inner[1] * 0.3);
var outerBuffer = CreateCanvas(outer[0], outer[1], false);
outerBuffer.context.font = outerFontSize + "px times";
outerBuffer.context.fillStyle = rgba2hex([0,0,0,1]);
var innerBuffer = CreateCanvas(inner[0], inner[1], true);
innerBuffer.context.font = innerFontSize + "px times";
innerBuffer.context.fillStyle = rgba2hex([0,0,0,1]);
innerBuffer.context.fillText("raster", 10, inner[1] * 0.9);
var startTime = GetSystemTimeMS();
function draw() {
var span = 5;
var phase = ((GetTimeDifferenceMS(startTime) / 1000) % span) / span;
outerBuffer.context.clearRect(0, 0, outer[0], outer[1]);
var x = 50 + phase * 20;
outerBuffer.context.fillText("vector", x, outer[1] * 0.5);
outerBuffer.context.drawImage(innerBuffer.canvas, x, 0);
window.setTimeout(draw, 10);
}
draw();
</script>
</body>
</html>

I can definitely reproduce it on both my stable chrome and on my canary.
I reported to the chromium team. Let's hope a fix will come soon enough.
For a workaround, you can shrink a little bit your images (minimum value I found was size * 0.99. This should force the antialiasing algorithm to kick in.
var outer = [200, 200];
var inner = [200, 200];
function CreateCanvas(w, h, hidden) {
var canvas = document.createElement('canvas');
if (!hidden) document.body.appendChild(canvas);
canvas.width = w;
canvas.height = h;
var context = canvas.getContext('2d');
return {
canvas: canvas,
context: context
};
}
function rgba2hex(color) {
return "rgba(" + Math.floor(color[0] * 255) + ',' + Math.floor(color[1] * 255) + ',' + Math.floor(color[2] * 255) + ',' + color[3] + ")";
}
function GetSystemTimeMS() {
return (new Date()).getTime();
}
function GetTimeDifferenceMS(time) {
return GetSystemTimeMS() - time;
}
var outerFontSize = Math.min(100, outer[1] * 0.3);
var innerFontSize = Math.min(100, inner[1] * 0.3);
var outerBuffer = CreateCanvas(outer[0], outer[1], false);
outerBuffer.context.font = outerFontSize + "px times";
outerBuffer.context.fillStyle = rgba2hex([0, 0, 0, 1]);
var innerBuffer = CreateCanvas(inner[0], inner[1], true);
innerBuffer.context.font = innerFontSize + "px times";
innerBuffer.context.fillStyle = rgba2hex([0, 0, 0, 1]);
innerBuffer.context.fillText("raster", 10, inner[1] * 0.9);
var startTime = GetSystemTimeMS();
function draw() {
var span = 5;
var phase = ((GetTimeDifferenceMS(startTime) / 1000) % span) / span;
outerBuffer.context.clearRect(0, 0, outer[0], outer[1]);
var x = 50 + phase * 20;
outerBuffer.context.fillText("vector", x, outer[1] * 0.5);
// shrink a little bit our image
outerBuffer.context.drawImage(innerBuffer.canvas, x, 0, 200 * 0.99, 200 * 0.99);
requestAnimationFrame(draw);
}
draw();

Related

graphics.beginStroke not working in IE11 or edge

I'm painting a ruler to the canvas. The ruler paints in chrome but not in IE or Edge.
The tick marks of the ruler are not painting. I think my problem is in set stroke. Does IE not support set stroke?
Any idea what I'm doing wrong?
I think the problem is in these two lines but I'm unsure.
division.graphics.setStrokeStyle(0.5).beginStroke("black");
backgroundOfDivision.graphics.drawRect(-pixelsPerDivision / 2, 200, pixelsPerDivision, divisionHeight).endStroke();
Link to the ruler game
function createRuler(lengthInInches, start) {
var ruler = new createjs.Container();
var pixelsPerDivision = settings.ruler.pixelsPerDivision;
var totalDivisions = settings.ruler.divisionsPerInch * (lengthInInches);
var cmPerInch = 2.54;
var mmPerInch = cmPerInch * 10;
var rectangle = new createjs.Shape();
var rulerHeight = 200;
rectangle.graphics.beginStroke("black").beginFill("white").drawRect(0, 200, totalDivisions * pixelsPerDivision, rulerHeight);
ruler.addChild(rectangle);
var divisionContainer;
var backgroundOfDivision;
var division, divisionHeight, numberText;
var end = start + totalDivisions;
var startDivision = start * settings.ruler.divisionsPerInch;
//Paint Standard Ruler
for (var i = 0; i <= totalDivisions; ++i) {
divisionContainer = new createjs.Container();
divisionContainer.value = i * (1 / settings.ruler.divisionsPerInch) + start;
divisionContainer.unit = "in";
backgroundOfDivision = new createjs.Shape();
division = new createjs.Shape();
division.x = i * pixelsPerDivision
division.graphics.setStrokeStyle(0.5).beginStroke("black");
if ((i + startDivision) % 32 == 0) {
// make big line
divisionHeight = 70;
if ((i + startDivision) > 0) {
var numberText = new createjs.Text(((i + startDivision) / 32).toString(), "32px Arial", "black");
numberText.x = division.x;
numberText.y = divisionHeight + 200;
numberText.textAlign = "center";
divisionContainer.addChild(numberText);
}
}
else if ((i + startDivision) % 8 == 0) {
// make 1/4 inch line
divisionHeight = 60;
}
else if ((i + startDivision) % 4 == 0) {
// make 1/8 inch line
divisionHeight = 45;
}
else if ((i + startDivision) % 2 == 0) {
// make 1/16 inch line
divisionHeight = 30;
}
else {
// make 1/32 inch line
divisionHeight = 15;
}
backgroundOfDivision.graphics.setStrokeStyle(0.5).beginStroke("Green").beginFill("Green");
backgroundOfDivision.alpha = 0.0;
backgroundOfDivision.graphics.drawRect(-pixelsPerDivision / 2, 200, pixelsPerDivision, divisionHeight).endStroke();
backgroundOfDivision.x = i * pixelsPerDivision;
division.graphics.drawRect(0, 200, 0, divisionHeight).endStroke();
divisionContainer.divisionHeight = divisionHeight;
divisionContainer.division = division;
divisionContainer.backgroundOfDivision = backgroundOfDivision;
divisionContainer.addChild(backgroundOfDivision);
divisionContainer.addEventListener("rollover", function (e) {
createjs.Tween.get(e.currentTarget.backgroundOfDivision).to({ alpha: 1.0 }, 500);
});
divisionContainer.addEventListener("rollout", function (e) {
createjs.Tween.get(e.currentTarget.backgroundOfDivision, { override: true }).to({ alpha: 0.0 }, 250);
});
divisionContainer.addEventListener("mousedown", function (e) {
if (clickedAnswerNowWait == false) {
btnClick();
clickedAnswerNowWait = true;
CheckAnswer(e.currentTarget)
}
});
divisionContainer.addChild(division);
ruler.addChild(divisionContainer);
allTheDivisions.push(divisionContainer);
}
}
The issue here is not with EaselJS beginStroke, but rather how browsers handle a 0-width rectangle.
To draw your ticks on your ruler, you are using:
division.graphics.beginStroke("green")
.drawRect(0, 200, 0, divisionHeight);
In Chrome, this will show the stroke, however IE/Edge does not. To illustrate this, I created a simple demo that just does a stroke on a raw canvas:
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,0,100);
ctx.stroke();
In Chrome, this shows a stroke, and IE/Edge it does not.
I would recommend instead using a stroke. It has the benefit of auto-centering as the stroke grows, and you can control the lineCap as well. If you want ticks that have a different fill/stroke, then rectangles are the way to go, as long as they are wider than 0.
Hope that helps!

Canvas arc and fill with gradient

I have the following source code:
HTML:
<canvas id="main" width="500" height="500" style="border:1px solid black;"></canvas>
JavaScript:
function myRnd(val)
{
return parseInt(Math.random() * val);
}
function rndCircles() {
var maxCircles = 30;
for (var r = 1; r <= maxCircles; r++) {
var c = document.getElementById("main");
var x = myRnd(c.clientWidth);
var y = myRnd(c.clientHeight);
var radius = parseInt(Math.random() * 30);
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, 'rgb(' + myRnd(255) + ', ' + myRnd(255) + ',' + myRnd(255) + ')');
grd.addColorStop(1, 'white');
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI,false);
// Fill with gradient
ctx.fillStyle = grd;
ctx.fill();
ctx.lineWidth = 5;
//ctx.strokeStyle = '#003300';
ctx.stroke();
}
}
rndCircles();
I cannot see each arc filled with a different color/gradient on Chrome. Why? Am I missing something?
Fiddle here:
https://jsfiddle.net/j9wst2yd/
The gradient will use the initial position and radius when defined, which means the arcs further away from it will eventually turn completely white (or whatever the outer color would be).
You can solve this by using translation instead of setting position for the arcs.
Only a couple of adjustments are needed -
Create the gradient based around origin (0, 0):
var grd = ctx.createRadialGradient(0, 0, 5, 0, 0, 100);
// ...
Then replace setting arc position with translation, here absolute using setTransform() instead (translate() would accumulate, forcing you to reverse the translation afterwards which is more performance costly):
ctx.setTransform(1,0,0,1, x, y); // two last = translation
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI,false); // draw at origin
To reset back to normal (identity matrix) just set (0,0) for setTransform():
ctx.setTransform(1, 0, 0, 1, 0, 0);
Adjust as needed.
function myRnd(val)
{
return parseInt(Math.random() * val);
}
function rndCircles() {
var maxCircles = 30;
var c = document.getElementById("main");
var ctx = c.getContext("2d");
for (var r = 1; r <= maxCircles; r++) {
var x = myRnd(c.clientWidth);
var y = myRnd(c.clientHeight);
var radius = parseInt(Math.random() * 30);
var grd = ctx.createRadialGradient(0, 0, 5, 0, 0, radius);
grd.addColorStop(0, 'rgb(' + myRnd(255) + ', ' + myRnd(255) + ',' + myRnd(255) + ')');
grd.addColorStop(1, 'white');
ctx.fillStyle = grd;
ctx.setTransform(1,0,0,1,x,y);
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI,false);
// Fill with gradient
ctx.fill();
ctx.lineWidth = 5;
//ctx.strokeStyle = '#003300';
ctx.stroke();
}
}
rndCircles();
<canvas id="main" width="500" height="500" style="border:1px solid black;"></canvas>

Html5 canvas scrolling vertically and horizontally

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#canvasOne
{
border: 1px solid black;
}
</style>
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
</head>
<body>
<div align="center">
<canvas id="canvasOne">
</canvas>
</div>
<script type="text/javascript">
var myCanvas = document.getElementById("canvasOne");
var myContext = myCanvas.getContext("2d");
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
init();
var numShapes;
var shapes;
var dragIndex;
var dragging;
var mouseX;
var mouseY;
var dragHoldX;
var dragHoldY;
var timer;
var targetX;
var targetY;
var easeAmount;
var bgColor;
var nodes;
var colorArr;
function init()
{
myCanvas.width = $(window).width() - 200;
myCanvas.height = $(window).height() - 200;
shapes = [];
nodes = ["0;Person;24828760;Alok Kumar;Gorakhpur;#F44336;28",
"0;Suspect;04/Dec/2016;4;Suman_Biswas;#3F51B5;20","1;Rule;4;Apparent Means;3 Parameter;#EEFF41;20",
"0;Policy;36QA649749;In-Force;Quarterly;#FF9800;20","3;Product;Pension;Saral Pension;SRPEN;#795548;20","3;Payment;Cheque;Realized;Lucknow;#0091EA;20",
"0;Policy;162348873;Lapsed;Quarterly;#FF9800;20","6;Product;Pension;Life-Long Pension;LLPP;#795548;20","6;Payment;Cheque;Realized;Gorakhpur;#0091EA;20",
"0;Policy;1EQF178639;Lapsed;Monthly;#FF9800;20","9;Product;Life;Shield;SHIELDA;#795548;20","9;Payment;Demand Draft;Realized;Lucknow;#0091EA;20"];
numShapes = nodes.length;
makeShapes();
drawScreen();
myCanvas.addEventListener("mousedown", mouseDownListener, false);
}
//drawing
function makeShapes()
{
var tempX;
var tempY;
for(var i = 0; i < numShapes; i++)
{
var centerX = myCanvas.width/2;
var centerY = myCanvas.height/2;
var nodeColor = nodes[i].split(";")[5];
var nodeRadius = nodes[i].split(";")[6];
var nodeConnect = nodes[i].split(";")[0];
if(i == 0)//center of circle
{
tempX = centerX
tempY = centerY;
}
else
{
//tempX = Math.random() * (myCanvas.width - tempRadius);
//tempY = Math.random() * (myCanvas.height - tempRadius);
//var x = x0 + r * Math.cos(2 * Math.PI * i / items);
//var y = y0 + r * Math.sin(2 * Math.PI * i / items);
//250 is the distance from center node to outside nodes it can be actual radius in degrees
tempX = shapes[nodeConnect].x + 300 * Math.cos(2 * Math.PI * i / numShapes);
tempY = shapes[nodeConnect].y + 300 * Math.sin(2 * Math.PI * i / numShapes);
}
tempShape = {x: tempX, y: tempY, rad: nodeRadius, color: nodeColor, text: nodes[i]};
shapes.push(tempShape);
}
}
//drawing both shape (line and circle) and screen
function drawScreen()
{
myContext.fillStyle = "#ffffff";
myContext.fillRect(0, 0, myCanvas.width, myCanvas.height);
drawShapes();
}
function drawShapes()
{
//line
for(var i = 1; i < numShapes; i++)
{
myContext.beginPath();
myContext.strokeStyle = "#B2B19D";
var nodeConnect = nodes[i].split(";")[0];
myContext.moveTo(shapes[nodeConnect].x, shapes[nodeConnect].y);
myContext.lineTo(shapes[i].x, shapes[i].y);
myContext.stroke();
}
//circle
for(var i = 0; i < numShapes; i++)
{
myContext.fillStyle = shapes[i].color;
myContext.beginPath();
myContext.arc(shapes[i].x, shapes[i].y, shapes[i].rad, 0, 2*Math.PI, false);
myContext.closePath();
myContext.fill();
}
//text
for(var i = 0; i < numShapes; i++)
{
myContext.beginPath();
myContext.font = '10pt Arial';
myContext.fillStyle = 'black';
var textarr = shapes[i].text.split(";");
myContext.fillText(textarr[1], shapes[i].x + 30, shapes[i].y - 24);
/*myContext.fillText(textarr[2], shapes[i].x + 30, shapes[i].y + 1);
myContext.fillText(textarr[3], shapes[i].x + 30, shapes[i].y + 22);
myContext.fillText(textarr[4], shapes[i].x + 30, shapes[i].y + 44);*/
myContext.closePath();
myContext.fill();
}
}
//animation
function mouseDownListener(evt)
{
var highestIndex = -1;
var bRect = myCanvas.getBoundingClientRect();
mouseX = (evt.clientX - bRect.left) * (myCanvas.width/bRect.width);
mouseY = (evt.clientY - bRect.top) * (myCanvas.height/bRect.height);
for(var i = 0; i < numShapes; i++)
{
if(hitTest(shapes[i], mouseX, mouseY))
{
dragging = true;
if(i > highestIndex)
{
dragHoldX = mouseX - shapes[i].x;
dragHoldY = mouseY - shapes[i].y;
highestIndex = i;
dragIndex = i;
}
}
}
if(dragging)
{
window.addEventListener("mousemove", mouseMoveListener, false);
}
myCanvas.removeEventListener("mousedown", mouseDownListener, false);
window.addEventListener("mouseup", mouseUpListener, false);
if(evt.preventDefault)
{
evt.preventDefault;
}
return false;
}
function mouseMoveListener(evt)
{
var shapeRad = shapes[dragIndex].rad;
var minX = shapeRad;
var maxX = myCanvas.width - shapeRad;
var minY = shapeRad;
var maxY = myCanvas.height - shapeRad;
//get mouse position correctly
var bRect = myCanvas.getBoundingClientRect();
mouseX = (evt.clientX - bRect.left)*(myCanvas.width / bRect.width);
mouseY = (evt.clientY - bRect.top)*(myCanvas.height / bRect.height);
//clamp x and y position to prevent object from dragging outside canvas
posX = mouseX - dragHoldX;
posX = (posX < minX) ? minX : ((posX > maxX) ? maxX : posX);
posY = mouseY - dragHoldY;
posY = (posY < minY) ? minY : ((posY > maxY) ? maxY : posY);
shapes[dragIndex].x = posX;
shapes[dragIndex].y = posY;
drawScreen();
}
function mouseUpListener(evt)
{
myCanvas.addEventListener("mousedown", mouseDownListener, false);
window.removeEventListener("mouseup", mouseUpListener, false);
if(dragging)
{
dragging = false;
window.removeEventListener("mousemove", mouseMoveListener, false);
}
}
function hitTest(shape, mx, my)
{
var dx = mx - shape.x;
var dy = my - shape.y;
return(dx * dx + dy * dy < shape.rad * shape.rad);
}
</script>
</body>
</html>
The following canvas animation creates nodes and edges. However due
to space constraint, some of the nodes are not visible due to canvas
height and width. Even adding overflow css to canvas dosen't help as
i am not able to scroll.
<canvas> context doesn't have a built-in scroll method.
You then have multiple ways to circumvent this limitation.
The first one, is as in #markE's answer, to scale your context's matrix so that your drawings fit into the required space. You could also refactor your code so that all coordinates are relative to the canvas size.
This way, you won't need scrollbars and all your drawings will just be scaled appropriately, which is the desirable behavior in most common cases.
But if you really need to have some scrolling feature, here are some ways :
The easiest and most recommended one : let the browser handle it.
You will have to set the size of your canvas to the maximum of your drawings, and wrap it in an other element which will scroll. By setting the overflow:auto css property on the container, our scrollbars appear and we have our scrolling feature.
In following example, the canvas is 5000px wide and the container 200px.
var ctx = canvas.getContext('2d');
ctx.textAlign = 'center';
for (var w = 0; w < canvas.width; w += 100) {
for (var h = 0; h < canvas.height; h += 100) {
ctx.fillText(w + ',' + h, w, h);
}
}
#container {
width: 200px;
height: 200px;
overflow: auto;
border: 1px solid;
}
canvas{
display: block;
}
<div id="container">
<canvas id="canvas" height="5000" width="5000"></canvas>
</div>
Main advantages :
easily implemented.
users are used to these scrollbars.
Main caveats :
You're limited by canvas maximum sizes.
If your canvas is animated, you'll also draw for each frame parts of the canvas that aren't visible.
You have small control on scrollbars look and you'll still have to implement drag-to-scroll feature yourself for desktop browsers.
A second solution, is to implement this feature yourself, using canvas transform methods : particularly translate, transform and setTransform.
Here is an example :
var ctx = canvas.getContext('2d');
var app = {};
// the total area of our drawings, can be very large now
app.WIDTH = 5000;
app.HEIGHT = 5000;
app.draw = function() {
// reset everything (clears the canvas + transform + fillStyle + any other property of the context)
canvas.width = canvas.width;
// move our context by the inverse of our scrollbars' left and top property
ctx.setTransform(1, 0, 0, 1, -app.scrollbars.left, -app.scrollbars.top);
ctx.textAlign = 'center';
// draw only the visible area
var visibleLeft = app.scrollbars.left;
var visibleWidth = visibleLeft + canvas.width;
var visibleTop = app.scrollbars.top
var visibleHeight = visibleTop + canvas.height;
// you probably will have to make other calculations than these ones to get your drawings
// to draw only where required
for (var w = visibleLeft; w < visibleWidth + 50; w += 100) {
for (var h = visibleTop; h < visibleHeight + 50; h += 100) {
var x = Math.round((w) / 100) * 100;
var y = Math.round((h) / 100) * 100;
ctx.fillText(x + ',' + y, x, y);
}
}
// draw our scrollbars on top if needed
app.scrollbars.draw();
}
app.scrollbars = function() {
var scrollbars = {};
// initial position
scrollbars.left = 0;
scrollbars.top = 0;
// a single constructor for both horizontal and vertical
var ScrollBar = function(vertical) {
var that = {
vertical: vertical
};
that.left = vertical ? canvas.width - 10 : 0;
that.top = vertical ? 0 : canvas.height - 10;
that.height = vertical ? canvas.height - 10 : 5;
that.width = vertical ? 5 : canvas.width - 10;
that.fill = '#dedede';
that.cursor = {
radius: 5,
fill: '#bababa'
};
that.cursor.top = vertical ? that.cursor.radius : that.top + that.cursor.radius / 2;
that.cursor.left = vertical ? that.left + that.cursor.radius / 2 : that.cursor.radius;
that.draw = function() {
if (!that.visible) {
return;
}
// remember to reset the matrix
ctx.setTransform(1, 0, 0, 1, 0, 0);
// you can give it any shape you like, all canvas drawings operations are possible
ctx.fillStyle = that.fill;
ctx.fillRect(that.left, that.top, that.width, that.height);
ctx.beginPath();
ctx.arc(that.cursor.left, that.cursor.top, that.cursor.radius, 0, Math.PI * 2);
ctx.fillStyle = that.cursor.fill;
ctx.fill();
};
// check if we're hovered
that.isHover = function(x, y) {
if (x >= that.left - that.cursor.radius && x <= that.left + that.width + that.cursor.radius &&
y >= that.top - that.cursor.radius && y <= that.top + that.height + that.cursor.radius) {
// we are so record the position of the mouse and set ourself as the one hovered
scrollbars.mousePos = vertical ? y : x;
scrollbars.hovered = that;
that.visible = true;
return true;
}
// we were visible last call and no wheel event is happening
else if (that.visible && !scrollbars.willHide) {
that.visible = false;
// the app should be redrawn
return true;
}
}
return that;
};
scrollbars.horizontal = ScrollBar(0);
scrollbars.vertical = ScrollBar(1);
scrollbars.hovered = null;
scrollbars.dragged = null;
scrollbars.mousePos = null;
// check both of our scrollbars
scrollbars.isHover = function(x, y) {
return this.horizontal.isHover(x, y) || this.vertical.isHover(x, y);
};
// draw both of our scrollbars
scrollbars.draw = function() {
this.horizontal.draw();
this.vertical.draw();
};
// check if one of our scrollbars is visible
scrollbars.visible = function() {
return this.horizontal.visible || this.vertical.visible;
};
// hide it...
scrollbars.hide = function() {
// only if we're not using the mousewheel or dragging the cursor
if (this.willHide || this.dragged) {
return;
}
this.horizontal.visible = false;
this.vertical.visible = false;
};
// get the area's coord relative to our scrollbar
var toAreaCoord = function(pos, scrollBar) {
var sbBase = scrollBar.vertical ? scrollBar.top : scrollBar.left;
var sbMax = scrollBar.vertical ? scrollBar.height : scrollBar.width;
var areaMax = scrollBar.vertical ? app.HEIGHT - canvas.height : app.WIDTH - canvas.width;
var ratio = (pos - sbBase) / (sbMax - sbBase);
return areaMax * ratio;
};
// get the scrollbar's coord relative to our total area
var toScrollCoords = function(pos, scrollBar) {
var sbBase = scrollBar.vertical ? scrollBar.top : scrollBar.left;
var sbMax = scrollBar.vertical ? scrollBar.height : scrollBar.width;
var areaMax = scrollBar.vertical ? app.HEIGHT - canvas.height : app.WIDTH - canvas.width;
var ratio = pos / areaMax;
return ((sbMax - sbBase) * ratio) + sbBase;
}
scrollbars.scroll = function() {
// check which one of the scrollbars is active
var vertical = this.hovered.vertical;
// until where our cursor can go
var maxCursorPos = this.hovered[vertical ? 'height' : 'width'];
var pos = vertical ? 'top' : 'left';
// check that we're not out of the bounds
this.hovered.cursor[pos] = this.mousePos < 0 ? 0 :
this.mousePos > maxCursorPos ? maxCursorPos : this.mousePos;
// seems ok so tell the app we scrolled
this[pos] = toAreaCoord(this.hovered.cursor[pos], this.hovered);
// redraw everything
app.draw();
}
// because we will hide it after a small time
scrollbars.willHide;
// called by the wheel event
scrollbars.scrollBy = function(deltaX, deltaY) {
// it's not coming from our scrollbars
this.hovered = null;
// we're moving horizontally
if (deltaX) {
var newLeft = this.left + deltaX;
// make sure we're in the bounds
this.left = newLeft > app.WIDTH - canvas.width ? app.WIDTH - canvas.width : newLeft < 0 ? 0 : newLeft;
// update the horizontal cursor
this.horizontal.cursor.left = toScrollCoords(this.left, this.horizontal);
// show our scrollbar
this.horizontal.visible = true;
}
if (deltaY) {
var newTop = this.top + deltaY;
this.top = newTop > app.HEIGHT - canvas.height ? app.HEIGHT - canvas.height : newTop < 0 ? 0 : newTop;
this.vertical.cursor.top = toScrollCoords(this.top, this.vertical);
this.vertical.visible = true;
}
// if we were called less than the required timeout
clearTimeout(this.willHide);
this.willHide = setTimeout(function() {
scrollbars.willHide = null;
scrollbars.hide();
app.draw();
}, 500);
// redraw everything
app.draw();
};
return scrollbars;
}();
var mousedown = function(e) {
// tell the browser we handle this
e.preventDefault();
// we're over one the scrollbars
if (app.scrollbars.hovered) {
// new promotion ! it becomes the dragged one
app.scrollbars.dragged = app.scrollbars.hovered;
app.scrollbars.scroll();
}
};
var mousemove = function(e) {
// check the coordinates of our canvas in the document
var rect = canvas.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
// we're dragging something
if (app.scrollbars.dragged) {
// update the mouse position
app.scrollbars.mousePos = app.scrollbars.dragged.vertical ? y : x;
app.scrollbars.scroll();
} else if (app.scrollbars.isHover(x, y)) {
// something has changed, redraw to show or hide the scrollbar
app.draw();
}
e.preventDefault();
};
var mouseup = function() {
// we dropped it
app.scrollbars.dragged = null;
};
var mouseout = function() {
// we're out
if (app.scrollbars.visible()) {
app.scrollbars.hide();
app.scrollbars.dragged = false;
app.draw();
}
};
var mouseWheel = function(e) {
e.preventDefault();
app.scrollbars.scrollBy(e.deltaX, e.deltaY);
};
canvas.addEventListener('mousemove', mousemove);
canvas.addEventListener('mousedown', mousedown);
canvas.addEventListener('mouseup', mouseup);
canvas.addEventListener('mouseout', mouseout);
canvas.addEventListener('wheel', mouseWheel);
range.onchange = function() {
app.WIDTH = app.HEIGHT = this.value;
app.scrollbars.left = 0;
app.scrollbars.top = 0;
app.draw();
};
// an initial drawing
app.draw();
canvas {border: 1px solid;}
span{font-size: .8em;}
<canvas id="canvas" width="200" height="150"></canvas>
<span>
change the total area size
<input type="range" min="250" max="5000000" steps="250" value="5000" id="range" />
</span>
Main advantages :
no limitation for the size of your drawing areas.
you can customize your scrollbars as you wish.
you can control when the scrollbars are enable or not.
you can get the visible area quite easily.
Main caveats:
a bit more code than the CSS solution...
no really, that's a lot of code...
A third way I wrote some time ago for an other question took advantage of the ability to draw an other canvas with ctx.drawImage(). It has its own caveats and advantages, so I let you pick the one you need, but this last one also had a drag and slide feature which can be useful.
So your node drawings don't fit on the canvas size?
You can easily "shrink" your content to fit the visible canvas with just 1 command!
The context.scale(horizontalRescale,verticalRescale) command will shrink every following drawing by your specified horizontalRescale & verticalRescale percentages.
An Important note: You must make horizontalRescale,verticalRescale the same value or your content will be distorted.
The nice thing about using context.scale is that you don't have to change any of the code that draws your nodes ... canvas automatically scales all those nodes for you.
For example, this code will shrink your nodes to 80% of their original size:
var downscaleFactor= 0.80;
context.scale( downscaleFactor, downscaleFactor );
Rather than go through your 200+ lines of code, I leave it to you to calculate downscaleFactor.

The canvas has been tainted by cross-origin data in chrome only

Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D':
The canvas has been tainted by cross-origin data
I am getting above error only in chrome. My code(following) works fine in mozilla. I have not corss domain issue. So why could i get above error in chrome?
var wheel_canvas, wheel_context, can_w, can_h, wheel_grd;
var LARGE_RADIUS = 160;
var SMALL_RADIUS = 120;
var wheel_canvas = document.getElementById('wheel_canvas');
var wheel_context = wheel_canvas.getContext('2d');
var can_w = $(wheel_canvas).width();
var can_h = $(wheel_canvas).height();
var centerX = can_w / 2, centerY = can_h / 2;
var wheel_grd = null;
test('#FF0000');
function test(hex)
{
$('#clrpicker').css({'left': 210, 'top': 210 });
inverted = hexBW(hex);
$('#color_val_show').val(hex);
current_color_hex_val_selected = hex;
$('#color_val_show').css({'color':inverted,'background':hex});
fillGradientCirle(hex);
}
function fillGradientCirle(hex)
{
wheel_context.rect(0, 0, can_w, can_h);
wheel_grd = wheel_context.createLinearGradient(1, 1, 0, can_w, can_h);
wheel_grd.addColorStop(1, '#ffffff');
wheel_grd.addColorStop(0.5, hex);
wheel_grd.addColorStop(0, '#000000');
wheel_context.fillStyle = wheel_grd;
wheel_context.beginPath();
wheel_context.arc(centerX, centerY, LARGE_RADIUS, 0, 2 * Math.PI);
wheel_context.fill();
}
$(wheel_canvas).click(function (e)
{
$.event.fix(e);
x = e.pageX;
y = e.pageY;
can_p = $(this).offset();
x = x - $(document).scrollLeft() - can_p.left;
// Fixed typo
y = y - $(document).scrollTop() - can_p.top;
if (Math.sqrt((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY)) < SMALL_RADIUS) return; // Precaution
$('#wheel_picker').css({ 'left': x-8 + 'px', 'top': y-8 + 'px' });
var data = wheel_context.getImageData(x, y, 1, 1).data;
pixelData = data;
rgbString = 'rgb(' + pixelData[0] + ', ' + pixelData[1] + ', ' + pixelData[2] + ')';
hex = rgb2hex(rgbString);
inverted = hexBW(hex);
$('#color_val_show').val(hex);
current_color_hex_val_selected = hex;
$('#color_val_show').css({'color':inverted,'background':hex});
$('#feedback').html("Coordinates : " + x + "," + y + " Color: " + hex);
});
If this is all the code and you don't use any cross-origin images then the only error that stand out is this line:
wheel_grd = wheel_context.createLinearGradient(1, 1, 0, can_w, can_h);
This should only have four arguments not five. The last argument may trip out Chrome in some way.
Try by changing it to:
// x0 y0 x1 y1
wheel_grd = wheel_context.createLinearGradient(1, 0, can_w, can_h);
Other errors you can consider looking at:
You are declaring the variables twice - the first var line in the example code is unnecessary
You are reading CSS size of canvas element, not its bitmap size (they are not the same).
To read proper dimension of canvas (unless you intended to read the CSS size for some reason) you need to use the following instead:
var can_w = wheel_canvas.width; //$(wheel_canvas).width();
var can_h = wheel_canvas.height; //$(wheel_canvas).height();
or if you insist on using jQuery:
var can_w = $(wheel_canvas).prop('width');
var can_h = $(wheel_canvas).prop('height');
Hope this helps!
For testing, you can also use --allow-file-access-from-files as a command-line argument to Chrome; this will allow you to use local files.

HTML5 Canvas: collision detection issues

I have this script I am working on that utilizes the oCanvas JS Library (http://ocanvas.org/) that creates an HTML5 canvas and displays multiple objects within the canvas. Currently, I have the script reading from an external XML document and loops through each project node and creates a circle object on the canvas.
I am having issues with trying to place this objects on the canvas evenly spaced from the middle circle (the logo variable in the code below).
// GLOBALS
var xmlData = '<?xml version="1.0" encoding="UTF-8"?><root name="CompanyName"><projects><project name="Project1"></project><project name="Project2"></project></projects></root>'
var xmlObj = []
// var angle = (360 * Math.PI)/180
var padding = 15
var canvas = oCanvas.create({
canvas: '#myCanvas'
})
var c_width = canvas.width
var c_height = canvas.height
var logo = canvas.display.ellipse({
x: c_width / 2,
y: c_height / 3,
radius: 80,
fill: '#d15851'
})
canvas.addChild(logo)
// var getXML = function(file){
// $.ajax({
// url: file,
// type: 'GET',
// dataType: 'xml',
// async: false,
// success: parseXML
// })
// }
var parseXML = function() {
var xmlDoc = $.parseXML(xmlData)
var xml = $(xmlDoc)
xml.find('project').each(function(i){
xmlObj[i] = canvas.display.ellipse({
fill: '#'+'0123456789abcdef'.split('').map(function(v,i,a){
return i>5 ? null : a[Math.floor(Math.random()*16)] }).join(''),
radius: 40,
opacity: 1
})
});
var angleSingleton = {
"currentAngle": 0,
"currentOffset": 0,
"incrementAngle": function() {
this.currentAngle = this.currentAngle + this.currentOffset
}
}
angleSingleton.currentOffset = Math.floor((360 * Math.PI)/xmlObj.length);
for(h = 0; h < xmlObj.length; h++) {
xmlObj[h].x = (logo.x + logo.radius * Math.cos(angleSingleton.currentAngle)) + xmlObj[h].radius + padding;
xmlObj[h].y = (logo.y + logo.radius * Math.sin(angleSingleton.currentAngle)) + xmlObj[h].radius + padding;
canvas.addChild(xmlObj[h])
angleSingleton.incrementAngle()
}
}
//
$(document).ready(function(){
parseXML()
})
What you want to take a look at is the Parametric equation for circles. Basically it defines a point along a circles perimeter at a specific angle. This answer covers it in more detail.
To get your x and y values for the new circle you use the following equations:
x = logo.x + logo.radius * Math.cos(angle)
y = logo.y + logo.radius * Math.sin(angle)
However you need to account for the room the new circle is going to take up plus any room for padding if you want it.
x = (logo.x + logo.radius * Math.cos(angle)) + newCircle.radius + circlePadding
y = (logo.y + logo.radius * Math.sin(angle)) + newCircle.radius + circlePadding
For the angle function try something like this:
var angleSingleton = {
"currentAngle": 0,
"currentOffset": 0,
"incrementAngle": function() {
this.currentAngle = this.currentAngle + this.currentOffset
}
}
angleSingleton.currentOffset = (360 * Math.PI)/xmlObj.length;
Then you can use this to keep track of the angle you need for the formula. To get the current angle use angleSingleton.currentAngle and replace angle++ with angleSingleton.incrementAngle
I ended up figuring it out!
// EXTENDING OBJECTS
Array.prototype.min = function(array) {
return Math.min.apply(Math, array);
}
Array.prototype.max = function(array) {
return Math.max.apply(Math, array)
}
//
// GLOBALS
var xmlData = '<?xml version="1.0" encoding="UTF-8"?><root name="CompanyName"><projects><project name="Project1"></project><project name="Project2"></project><project name="Project3"></project></projects></root>'
var xmlObj = []
var xmlDoc, xml;
var padding = 15
var canvas = oCanvas.create({
canvas: '#myCanvas'
})
var c_width = canvas.width
var c_height = canvas.height
var logo = canvas.display.ellipse({
x: c_width / 2,
y: c_height / 3,
radius: 80,
fill: '#d15851'
})
var rectObj = function(){
this.x = 0;
this.y = 0;
this.width = 100;
this.height = 100;
this.size = this.width + this.height; //this would equate to a circles radius if dealing with circles
this.fillerText = null;
this.fillRect = function(hexVal){
if(!hexVal)
return '#'+'0123456789abcdef'.split('').map(function(v,i,a){
return i>5 ? null : a[Math.floor(Math.random()*16)] }).join('')
else
return hexVal
};
this.drawRect = function(){
return canvas.display.rectangle({
width: this.width,
height: this.height,
fill: this.fillRect(),
x: this.x,
y: this.y
})
};
this.checkCollisions = function(objToCheck) {
var centerA = { x: this.x+(this.size/2), y: this.y+(this.size/2) };
var centerB = { x:objToCheck.x+(objToCheck.size/2), y: objToCheck.y+(objToCheck.size/2) };
var distance = Math.sqrt(((centerB.x-centerA.x)*(centerB.x-centerA.x) + (centerB.y-centerA.y)*(centerB.y-centerA.y)));
if(distance < (this.size+objToCheck.size)) {
objToCheck.x = this.x - (canvas.width/4)
objToCheck.fillRect = function(){
return 'red'
}
}
}
}
canvas.addChild(logo)
var parseXML = function() {
xmlDoc = $.parseXML(xmlData)
xml = $(xmlDoc)
xml.find('project').each(function(i){
xmlObj[i] = new rectObj()
xmlObj[i].fillerText = $(this).attr('name')
xmlObj[i].x = (logo.x + logo.radius * Math.cos((360*Math.PI) / (i + 1)) + padding) + ((xmlObj[i].width / 2) + (i+1));
xmlObj[i].y = (logo.y + logo.radius * Math.sin((360*Math.PI) / (i + 1)) + padding);
});
for(i = 0; i < xmlObj.length; i++) {
for(a = i+1; a < xmlObj.length; a++) {
xmlObj[i].checkCollisions(xmlObj[a])
}
canvas.addChild(xmlObj[i].drawRect())
}
}
//
$(document).ready(function(){
parseXML()
})
Screen shot:
I obviously need to write in the Y coords for the rectangles so that they're not touching the main circle, but for now, they all "float" as they're supposed to :)
Thanks for all of your help Devin!
BTW, I was able to write my collision algorithm by studying this JS file: http://andersonferminiano.com/html5/studies/balls_collisions/collision.js