How to draw circles OVER an image background of a HTML5 canvas? - javascript

So I'm drawing a world map to a canvas. I want this world map to plot the coordinates of things dynamically by drawing circles with the arc method. I draw the world map to the canvas, get a URL for the canvas, and there are no errors in drawing the circles... The only problem is the circles are being drawn underneath the image background. Here is my code.
// The containing function is a method of an object.
createCanvas: function(done) {
var imageObj = new Image();
imageObj.onload = _.bind(function(){
var canvas = document.createElement("canvas"),
context = canvas.getContext('2d'),
w = imageObj.width,
h = imageObj.height;
canvas.width = w;
canvas.height = h;
context.drawImage(imageObj, 0, 0, w, h);
for(var i = 0; i < arrayOfCoords.length; i++){
var mapPoint = arrayOfCoords[i];
//Invoke a function that gets an object {long: x, lat: y}
var coordinates = returnCoordinatesObject(mapPoint.long, mapPoint.lat)
context.beginPath();
context.arc(coordinates, long, coordinates.lat, 10, 0, Math.PI*2, true);
context.closePath();
context.fill();
}
var canvasImage = canvas.toDataURL('image/png');
console.log(canvasImage);
done.call(this, canvasImage);
}, this);
imageObj.src="img/le-world-map.png";
},
The code isn't erroring so I presume the circles are being drawn, but drawn behind the map. There are other threads on stackoverflow that have asked similar questions but I found them unclear and was unable to implement the solutions suggested...
Thx
--Gaweyne

Related

best practice in drawing outline of image

I've tried 3 ways to make it, but the effect doesn't looks well.
copy and fill image then make offset. The demo is
var ctx = canvas.getContext('2d'),
img = new Image;
img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";
function draw() {
var dArr = [-1,-1, 0,-1, 1,-1, -1,0, 1,0, -1,1, 0,1, 1,1], // offset array
s = 20, // thickness scale
i = 0, // iterator
x = 5, // final position
y = 5;
// draw images at offsets from the array scaled by s
for(; i < dArr.length; i += 2)
ctx.drawImage(img, x + dArr[i]*s, y + dArr[i+1]*s);
// fill with color
ctx.globalCompositeOperation = "source-in";
ctx.fillStyle = "red";
ctx.fillRect(0,0,canvas.width, canvas.height);
// draw original image in normal mode
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>
. When the outline width is large, the outline result will be wrong.
check the edge of image base on the Marching Squares algorithm. When the image shape is circle, the outline is with sawtooth. If make the outline more smoother, it won't fit the sharp shape like star.
copy and fill the image then scale it. When a image width is not equal with height, it doesn't work.
You can try with a math approach, without the offset array
var ctx = canvas.getContext('2d'),
img = new Image;
img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";
function draw() {
var s = 20, // thickness scale
x = 5, // final position
y = 5;
for (i=0; i < 360; i++)
ctx.drawImage(img, x + Math.sin(i) * s, y + Math.cos(i) * s);
// fill with color
ctx.globalCompositeOperation = "source-in";
ctx.fillStyle = "red";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// draw original image in normal mode
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>
My idea comes from the way we draw a circle using a string:
https://www.wikihow.com/Draw-a-Perfect-Circle-Using-a-Pin
Imagine that instead of a pencil at the end of the string we just have a shape
Here is a visual comparison of my approach and yours, also I'm showing a third approach scaling the image, there is really not a best one, it's just a matter of personal preference.
You could create a hybrid mode, if the hairline is important to you, get that portion of the image scaling it, then use a different way for the rest of the body.

Pixi js fill shape with a texture from canvas

I am trying to figure out a way I can fill a shape in PIXI.js using a texture created from a canvas.
The reason for this is I wanna be able to create a gradient on a normal html canvas, and they make a texture out of it and add it to the pixi stage. Now I can do that, that was the first thing I tested, it works. But the end goal is to create shapes in PIXI.js using the Graphics class and then fill them with my gradient. I do not know how to accomplish this, as the .beginFill() method only accepts a color. How do I fill a shape with a texture?
Here is my code. I know the auxillary canvas creation is a little verbose, but that is a problem for later.
$(document).ready(function() {
var stage = new PIXI.Container();
var renderer = PIXI.autoDetectRenderer(800, 600);
document.body.appendChild(renderer.view);
//Aliases
var Sprite = PIXI.Sprite;
var TextureCache = PIXI.utils.TextureCache;
var resources = PIXI. loader.resources;
function AuxCanvas(id, w, h, color1, color2) {
this.id = id;
this.w = w;
this.h = h;
this.color1 = color1;
this.color2 = color2;
}
// create and append the canvas to body
AuxCanvas.prototype.create = function() {
$('body').append('<canvas id="'+
this.id+'" width="'+
this.w+'" height="'+
this.h+'"></canvas>');
}
// draw gradient
AuxCanvas.prototype.drawGradient = function() {
var canvas = document.getElementById(this.id);
var ctx = canvas.getContext('2d');
var gradient = ctx.createLinearGradient(0, 0, 800, 0);
gradient.addColorStop(0, this.color1);
gradient.addColorStop(1, this.color2);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, this.w, this.h);
}
function setup() {
var graphics = new PIXI.Graphics();
graphics.beginFill(PIXI.Texture.fromCanvas(can1)); //This doesn't work obviously
graphics.drawCircle(60, 185, 40);
graphics.endFill();
stage.addChild(graphics);
renderer.render(stage);
}
var can1 = new AuxCanvas("can1", 800, 600, "green", "yellow");
can1.create();
can1.drawGradient();
var can2 = new AuxCanvas("can2", 800, 600, "blue", "red");
can2.create();
can2.drawGradient();
setup();
})
Allright I figured out a way, actually it was easy.
Just make the Graphics object a mask for the sprite created from the html canvas.
function setup() {
var can2 = document.getElementById('can2');
var sprite = new Sprite(PIXI.Texture.fromCanvas(can2))
var graphics = new PIXI.Graphics();
graphics.beginFill();
graphics.drawCircle(300, 300, 200);
graphics.endFill();
sprite.mask = graphics;
stage.addChild(sprite);
renderer.render(stage);
}
Moreover, appending the graphic as a child of the sprite is the best way to go, just need to make sure that they are the same dimentions. With this done, I can move the sprite freely, and it's gradient texture doesn't change, or more precisely, it moves with the sprite. Of course everything has to be equal in dimentions.
var graphics = new PIXI.Graphics();
graphics.beginFill();
graphics.drawCircle(100, 100, 100);
graphics.endFill();
sprite.addChild(graphics);
sprite.mask = graphics;

Canvas. How to get background pixels before drawing

I created a small plug-in for my map application. This plug-in adds text labels to geometric features. It looks like so:
On the screen above you can see a map, a horizontal linestring and a text label. I created this label by using canvas, canvas.getContext("2d") and a bunch of standard functions like ctx.strokeText, ctx.fillText etc. The problem I face now is that the linestring on the screen is interactive or moveable and I want my label to move as well. I'm not asking about the exact solution to my problem. What I'm interested in is just how to get backround pixels (right below my text label), so that I could restore them before I "move" or redraw the label at a new place. If you can provide a teeny-weeny example where you have some background and then draw some object and then "remove" it, it will be great.
You probably want to use context.getImageData and context.putImageData
Assuming your canvas has the id "myCanvas", calling doDraw() will cause a black rectangle to blink on a complex background.
First, the background is drawn in doDraw(). Then, the background that is to be covered by the rectangle is captured in drawRectangle() and saved in the variable "imageData". Then the rectangle is drawn over the background. Then, 1 second later, eraseRectangle() is called, and the background is replaced by a call to putImageData().
In this fiddle:
https://jsfiddle.net/f3Luxcoc/
Here's the javascript:
//coordinates of rectangle
var xp = 20;
var yp = 20;
var wp = 80;
var hp = 80;
//saved background image
var imageData = null;
function doDraw() {
var can = document.getElementById("myCanvas");
can.width = 500;
can.height = 500;
var context = can.getContext("2d");
//draw background contents
var image = getImage();
context.drawImage(image, 0, 0);
context.drawImage(image, 100, 0);
context.drawImage(image, 0, 100);
context.drawImage(image, 100, 100);
drawRectangle();
}
function drawRectangle() {
var can = document.getElementById("myCanvas");
var context = can.getContext("2d");
//capture background
imageData = context.getImageData(xp, yp, wp, hp);
//draw Rectangle
context.rect(xp, yp, wp, hp);
context.fill();
setTimeout(function() {
eraseRectangle();
}, 1000);
}
function eraseRectangle() {
var can = document.getElementById("myCanvas");
var context = can.getContext("2d");
context.putImageData(imageData, xp, yp);
setTimeout(function() {
drawRectangle();
}, 1000);
}
doDraw();
function getImage() {
var image1 = new Image(237, 110);
image1.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAO0AAABuCAMAAAD8t2TLAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAC1QTFRF////LVcpkauOZYdhrsStx9jF1uTV+//66PPn8vzy4uji7vft4O3f+P/38fPwC7dd6gAACdxJREFUeNrsXIti2yoMNYiHiSH//7kXCXD8AmTaddudta1zEht0QOhIgnSaHnnkkUceeeSRv1vszzRlv7OjL2hoUZEwTSHUNHIsoLYJ1oYBvE2tjnfu1Nw85DbNWCVAx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5 canvas

I need to erase any of the shapes(like circle, rect) but not whole context, using another brush tool.
var brush = new Path.Circle({
center: event.point,
radius: 35,
fillColor: 'red',
});
var eraser = new Path.Circle({
center: event.point,
radius: 35
});
I tried "destination-out", "clearRect", but nothing work. I need the result exactly similar the attached image.
You can use a second canvas, where you'll draw your background, and then, thanks to the destination-atop composite mode, keep only the wanted circle of this image, that you'll draw back to your main canvas.
var eraser = function(evt){
var x = evt.clientX - this.offsetLeft;
var y = evt.clientY - this.offsetTop;
oCtx.globalCompositeOperation = 'source-over';
oCtx.drawImage(img, 0,0);
oCtx.globalCompositeOperation = 'destination-atop';
oCtx.beginPath();
oCtx.arc(x, y, 25, 0, Math.PI*2);
oCtx.fill();
ctx.drawImage(offCan, 0,0);
}
main.addEventListener('mousemove', eraser);
var ctx = main.getContext('2d');
var offCan = main.cloneNode(true);
var oCtx = offCan.getContext('2d');
var draw = function(){
ctx.drawImage(this, 0,0);
ctx.fillStyle = 'red';
for(var i=0; i<12; i++){
ctx.beginPath();
ctx.arc(Math.random()*300, Math.random()*150, (Math.random()*25)+10, 0, Math.PI*2);
ctx.fill();
}
};
var img = new Image();
img.onload = draw;
img.src = "http://lorempixel.com/300/150";
// you should not include it in the doc, it's just for explaining how it works.
document.body.appendChild(offCan)
<canvas id="main"></canvas>

blend two images on a javascript canvas

How do you blend two arrays of pixel data to create one image? with the option of using different blending modes?
Pixastic is a special framework for advanced use of canvas, here are blending examples: http://www.pixastic.com/lib/docs/actions/blend/
If you would like do this alone, you can extract pixel data from 2 images, blend it with a mathematical equation, and put into a canvas. Here is information how to get and put pixel data from/to canvas:
http://ajaxian.com/archives/canvas-image-data-optimization-tip
Update:
Simple example with alpha blending of 2 images in proportion 50-50.
(Images borrowed from http://www.pixastic.com/sample/Butterfly.jpg and http://www.pixastic.com/sample/Flower.jpg )
<img src="Butterfly.jpg" id="img1">
<img src="Flower.jpg" id="img2">
<p>Blended image<br><canvas id="canvas"></canvas></p>
<script>
window.onload = function () {
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = img1.width;
var height = img1.height;
canvas.width = width;
canvas.height = height;
var pixels = 4 * width * height;
context.drawImage(img1, 0, 0);
var image1 = context.getImageData(0, 0, width, height);
var imageData1 = image1.data;
context.drawImage(img2, 0, 0);
var image2 = context.getImageData(0, 0, width, height);
var imageData2 = image2.data;
while (pixels--) {
imageData1[pixels] = imageData1[pixels] * 0.5 + imageData2[pixels] * 0.5;
}
image1.data = imageData1;
context.putImageData(image1, 0, 0);
};
</script>
I have created a separate, lightweight, open-source library for perform Photoshop-style blend modes from one HTML Canvas context to another: context-blender. Here's the sample usage:
// Might be an 'offscreen' canvas
var over = someCanvas.getContext('2d');
var under = anotherCanvas.getContext('2d');
over.blendOnto( under, 'screen', {destX:30,destY:15} );
See the README for more information.
I am tasked with recreating this java applet using JavaScript (must be tablet friendly, and work in all modern browsers > IE8).
I am creating images using: var image1 = new Image(); and then setting source: img.src = "some path";
So, from pepkin88 I see that the following function will blend two images by combining their pixel array data, overriding previous data from the first image with the new blended data, and finally putting the new data on the canvas resulting in a blended image:
window.onload = function () {
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = img1.width;
var height = img1.height;
canvas.width = width;
canvas.height = height;
var pixels = 4 * width * height;
context.drawImage(img1, 0, 0);
var image1 = context.getImageData(0, 0, width, height);
var imageData1 = image1.data;
context.drawImage(img2, 0, 0);
var image2 = context.getImageData(0, 0, width, height);
var imageData2 = image2.data;
while (pixels--) {
imageData1[pixels] = imageData1[pixels] * 0.5 + imageData2[pixels] * 0.5;
}
image1.data = imageData1;
context.putImageData(image1, 0, 0); };
HOWEVER, if you viewed the java applet that I'm responsible for recreating, you see that blending happens in real-time continuously as you drag the image around with the pointer the images are constantly blending based on their overlapped regions..
SO, I'm looking to modify the code to account for this, and I continually have the x, y, positions of images drawn (based on top left corner), and the w, h of all images stays static:
the following snippets don't include everything I'm doing, just what I sense is important for you to know
//Rectangle Class from Java converted to JS
function Rectangle(x, y, width, height, src) {
this.x = x;
this.y = y;
this.w = width;
this.h = height;
this.img = new Image();
this.img.src = src;
}
//Stores instance in rect array
rect[0] = new Rectangle(1, (height - 111)/2, 150, 105, "images/mMain.png");
//Draw method that's called
Rectangle.prototype.draw = function(ctx) {
//this.checkBound();
ctx.drawImage(this.img, this.x, this.y, this.w, this.h);
prepareMix(this.img, this.x, this.y, this.w, this.h);
}
So, I'm working on a prepareMix function that receives image info and uses it to get and store image data:
function prepareMix(src, x, y, w, h) {
pixels = 4 * w * h;
var image = mtx.getImageData(x, y, w, h);
var imgData = image.data;
}
Made a list of what to do:
Sense the overlapping
Get and Store the overlapping image data
Mix the overlapping region data arrays
Replace the overlapping image data with the blended data
Put the new data on the canvas
1. Sense the Overlapping:
Plan: Store image positions and compare positions data to know whether or not overlapping is occurring.
IF overlapping is TRUE, which two images is it true for? Distinguish these images that're overlapping from other images so that methods can be called on them.
js, css, html, and images in zip here BOX

Categories