I have a html5 canvas where you can erase the blur on top of an image. I would like to replace the blur with another image. I would like the end result to be once you erase the top image the bottom image will appear below it. I have been using an easeljs demo as a template.
http://www.createjs.com/#!/EaselJS/demos/alphamask
I feel like what I need to edit is in the html page script but it might be much deeper than that.
(Full code can be viewed here)
HTML
<canvas id="testCanvas" width="960" height="400"></canvas>
JavaScript
var stage;
var isDrawing;
var drawingCanvas;
var oldPt;
var oldMidPt;
var displayCanvas;
var image;
var bitmap;
var maskFilter;
var cursor;
var text;
var blur;
function init() {
if (window.top != window) {
document.getElementById("header").style.display = "none";
}
document.getElementById("loader").className = "loader";
image = new Image();
image.onload = handleComplete;
image.src = "images/summer.jpg";
stage = new createjs.Stage("testCanvas");
text = new createjs.Text("Loading...", "20px Arial", "#999999");
text.set({x:stage.canvas.width/2, y:stage.canvas.height-80});
text.textAlign = "center";
}
function handleComplete() {
document.getElementById("loader").className = "";
createjs.Touch.enable(stage);
stage.enableMouseOver();
stage.addEventListener("stagemousedown", handleMouseDown);
stage.addEventListener("stagemouseup", handleMouseUp);
stage.addEventListener("stagemousemove", handleMouseMove);
drawingCanvas = new createjs.Shape();
bitmap = new createjs.Bitmap(image);
blur = new createjs.Bitmap(image);
blur.filters = [new createjs.BoxBlurFilter(15,15,2)];
blur.cache(0,0,960,400);
blur.alpha = .5;
text.text = "Click and Drag to Reveal the Image.";
stage.addChild(blur, text, bitmap);
updateCacheImage(false);
cursor = new createjs.Shape(new createjs.Graphics().beginFill("#FFFFFF").drawCircle(0,0,20));
cursor.cursor = "pointer";
stage.addChild(cursor);
}
function handleMouseDown(event) {
oldPt = new createjs.Point(stage.mouseX, stage.mouseY);
oldMidPt = oldPt;
isDrawing = true;
}
function handleMouseMove(event) {
cursor.x = stage.mouseX;
cursor.y = stage.mouseY;
if (!isDrawing) {
stage.update();
return;
}
var midPoint = new createjs.Point(oldPt.x + stage.mouseX>>1, oldPt.y+stage.mouseY>>1);
drawingCanvas.graphics.setStrokeStyle(40, "round", "round")
.beginStroke("rgba(0,0,0,0.15)")
.moveTo(midPoint.x, midPoint.y)
.curveTo(oldPt.x, oldPt.y, oldMidPt.x, oldMidPt.y);
oldPt.x = stage.mouseX;
oldPt.y = stage.mouseY;
oldMidPt.x = midPoint.x;
oldMidPt.y = midPoint.y;
updateCacheImage(true);
}
function handleMouseUp(event) {
updateCacheImage(true);
isDrawing = false;
}
function updateCacheImage(update) {
if (update) {
drawingCanvas.updateCache(0, 0, image.width, image.height);
} else {
drawingCanvas.cache(0, 0, image.width, image.height);
}
maskFilter = new createjs.AlphaMaskFilter(drawingCanvas.cacheCanvas);
bitmap.filters = [maskFilter];
if (update) {
bitmap.updateCache(0, 0, image.width, image.height);
} else {
bitmap.cache(0, 0, image.width, image.height);
}
stage.update();
}
If you simply want to replace the blur-image, you have to change the following parts:
Add this after the loading of the first image:
image.src = "images/summer.jpg";
// add new part
image2 = new Image();
image2.onload = handleComplete;
image2.src = "images/your_newImage.jpg";
In the handleComplete() you now wait for 2 images to be loaded, so you add this:
function handleComplete() {
loaded++; // and initialize this variable in the very top with: var loaded = 0;
if ( window.loaded < 2 ) return;
//... other stull
and finally you change the following lines:
// old
blur = new createjs.Bitmap(image);
blur.filters = [new createjs.BoxBlurFilter(15,15,2)];
blur.cache(0,0,960,400);
blur.alpha = .5;
// new
blur = new createjs.Bitmap(image2);
This should now replace the blurred image with your desired image, it's not the best way, but it should get you there. I recommend you to start with some tutorial if you are planing to do more "deeper" stuff ;)
a common, though kinda janky, way is to re-size your canvas real quick. so changing your <canvas> elements width and height attributes. This will erase everything in your canvas.
Once that is done, reset it back to what you want it to be right away, and redraw the bottom image.
As I said this method is kinda sketchy but it does get the job done.
Related
I have a JavaScript script that I am getting an error for that I can't figure out. I am trying to take a picture of the webcam feed using JavaScript
The error is:
Uncaught TypeError: webcam.snap is not a function
I am using webcam.js to take the snapshot.
Here is my JavaScript code:
<script>
var video = document.createElement("video");
var canvasElement = document.getElementById("canvas");
var canvas = canvasElement.getContext("2d");
var loadingMessage = document.getElementById("loadingMessage");
var outputContainer = document.getElementById("output");
var outputMessage = document.getElementById("outputMessage");
var outputData = document.getElementById("outputData");
const jsQR = require("jsqr");
function drawLine(begin, end, color) {
canvas.beginPath();
canvas.moveTo(begin.x, begin.y);
canvas.lineTo(end.x, end.y);
canvas.lineWidth = 4;
canvas.strokeStyle = color;
canvas.stroke();
}
// Use facingMode: environment to attemt to get the front camera on phones
navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } }).then(function(stream) {
video.srcObject = stream;
video.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
video.play();
requestAnimationFrame(tick);
});
function tick() {
loadingMessage.innerText = "⌛ Loading video..."
if (video.readyState === video.HAVE_ENOUGH_DATA) {
loadingMessage.hidden = true;
canvasElement.hidden = false;
outputContainer.hidden = false;
canvasElement.height = video.videoHeight;
canvasElement.width = video.videoWidth;
canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
var imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
var code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: "invertFirst",
});
if (code) {
drawLine(code.location.topLeftCorner, code.location.topRightCorner, "#FF3B58");
drawLine(code.location.topRightCorner, code.location.bottomRightCorner, "#FF3B58");
drawLine(code.location.bottomRightCorner, code.location.bottomLeftCorner, "#FF3B58");
drawLine(code.location.bottomLeftCorner, code.location.topLeftCorner, "#FF3B58");
outputMessage.hidden = true;
outputData.parentElement.hidden = false;
outputData.innerText = code.data;
takeSnapShot();
}
else {
outputMessage.hidden = false;
outputData.parentElement.hidden = true;
}
}
requestAnimationFrame(tick);
}
// TAKE A SNAPSHOT.
takeSnapShot = function () {
webcam.snap(function (data_uri) {
downloadImage('video', data_uri);
});
}
// DOWNLOAD THE IMAGE.
downloadImage = function (name, datauri) {
var a = document.createElement('a');
a.setAttribute('download', name + '.png');
a.setAttribute('href', datauri);
a.click();
}
</script>
This is the first line that causes a problem:
webcam.snap(function (data_uri) {
downloadImage('video', data_uri);
});
This is the second line that causes a problem:
takeSnapShot();
how do I correct this properly?
****** UPDATE ******
The version of webcam.js I am using is WebcamJS v1.0.26. My application is a Django application that launches the HTML file as defined in main.js.
snap: function(user_callback, user_canvas) {
// use global callback and canvas if not defined as parameter
if (!user_callback) user_callback = this.params.user_callback;
if (!user_canvas) user_canvas = this.params.user_canvas;
// take snapshot and return image data uri
var self = this;
var params = this.params;
if (!this.loaded) return this.dispatch('error', new WebcamError("Webcam is not loaded yet"));
// if (!this.live) return this.dispatch('error', new WebcamError("Webcam is not live yet"));
if (!user_callback) return this.dispatch('error', new WebcamError("Please provide a callback function or canvas to snap()"));
// if we have an active preview freeze, use that
if (this.preview_active) {
this.savePreview( user_callback, user_canvas );
return null;
}
// create offscreen canvas element to hold pixels
var canvas = document.createElement('canvas');
canvas.width = this.params.dest_width;
canvas.height = this.params.dest_height;
var context = canvas.getContext('2d');
// flip canvas horizontally if desired
if (this.params.flip_horiz) {
context.translate( params.dest_width, 0 );
context.scale( -1, 1 );
}
// create inline function, called after image load (flash) or immediately (native)
var func = function() {
// render image if needed (flash)
if (this.src && this.width && this.height) {
context.drawImage(this, 0, 0, params.dest_width, params.dest_height);
}
// crop if desired
if (params.crop_width && params.crop_height) {
var crop_canvas = document.createElement('canvas');
crop_canvas.width = params.crop_width;
crop_canvas.height = params.crop_height;
var crop_context = crop_canvas.getContext('2d');
crop_context.drawImage( canvas,
Math.floor( (params.dest_width / 2) - (params.crop_width / 2) ),
Math.floor( (params.dest_height / 2) - (params.crop_height / 2) ),
params.crop_width,
params.crop_height,
0,
0,
params.crop_width,
params.crop_height
);
// swap canvases
context = crop_context;
canvas = crop_canvas;
}
// render to user canvas if desired
if (user_canvas) {
var user_context = user_canvas.getContext('2d');
user_context.drawImage( canvas, 0, 0 );
}
// fire user callback if desired
user_callback(
user_canvas ? null : canvas.toDataURL('image/' + params.image_format, params.jpeg_quality / 100 ),
canvas,
context
);
};
// grab image frame from userMedia or flash movie
if (this.userMedia) {
// native implementation
context.drawImage(this.video, 0, 0, this.params.dest_width, this.params.dest_height);
// fire callback right away
func();
}
else if (this.iOS) {
var div = document.getElementById(this.container.id+'-ios_div');
var img = document.getElementById(this.container.id+'-ios_img');
var input = document.getElementById(this.container.id+'-ios_input');
// function for handle snapshot event (call user_callback and reset the interface)
iFunc = function(event) {
func.call(img);
img.removeEventListener('load', iFunc);
div.style.backgroundImage = 'none';
img.removeAttribute('src');
input.value = null;
};
if (!input.value) {
// No image selected yet, activate input field
img.addEventListener('load', iFunc);
input.style.display = 'block';
input.focus();
input.click();
input.style.display = 'none';
} else {
// Image already selected
iFunc(null);
}
}
else {
// flash fallback
var raw_data = this.getMovie()._snap();
// render to image, fire callback when complete
var img = new Image();
img.onload = func;
img.src = 'data:image/'+this.params.image_format+';base64,' + raw_data;
}
return null;
},
Your implementation doesn't need Webcamjs, because you're using navigator media devices.
You can either use WebcamJS by initializing it at first and attaching it to some canvas, like in the following code
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
Or you can update your takeSnapShot function to the following :
takeSnapShot = function () {
downloadImage('video',canvasElement.toDataURL())
// Webcam.snap(function (data_uri) {
// downloadImage('video', data_uri);
// });
}
Here's a working example based on your code https://codepen.io/majdsalloum/pen/RwVKBbK
It seems like either:
the webcam's code are missing (not imported)
in this case you need to first call the script from the URL and add it with script tag
<script src="WEBCAM_JS_SOURCE">
or
they are imported, but used with typo. From the webcam source code it is defined as:
var Webcam = {
version: '1.0.26',
// globals
...
};
so you should use with a capital one.
Importing a picture to EaselJS with Bitmap:
var stage;
$(document).ready(function(){
var gameCanvas = document.getElementById("game");
stage = new createjs.Stage(gameCanvas);
loadPics();
function loadPics() {
let image = new Image();
image.src = "assets/img/island1.png";
image.onload = loadPic;
}
function loadPic(event) {
let bitmap = new createjs.Bitmap(event.target);
bitmap.scaleX = 1;
bitmap.scaleY = 1;
bitmap.image.width = gameCanvas.width;
stage.addChild(bitmap);
stage.update();
}
});
It doesn't matter if I export the picture from photoshop with 400x400 or 200x200
The picture is still all over the canvas.
If i scale it down
bitmap.scaleX = 0.2;
bitmap.scaleY = 0.2;
It becomes extremely blurred
Anyone knows a fix?
Canvas output can get pixelated if scaled with CSS
Make sure you're not adjusting canvas size in CSS but directly on the canvas element via either HTML or JS, otherwise canvas output can get distorted.
var stage;
$(document).ready(function(){
var gameCanvas = document.getElementById("game"),
windowWidth = $(window).width(),
windowHeight = $(window).height();
$(gameCanvas).width(windowWidth+'px');
$(gameCanvas).height(windowHeight+'px');
stage = new createjs.Stage(gameCanvas);
loadPics();
function loadPics() {
let image = new Image();
image.src = "assets/img/island1.png";
image.onload = loadPic;
}
function loadPic(event) {
let bitmap = new createjs.Bitmap(event.target);
bitmap.scaleX = 1;
bitmap.scaleY = 1;
bitmap.image.width = gameCanvas.width;
stage.addChild(bitmap);
stage.update();
}
});
I'm trying to create an animation in javascript.
I created a canvas
<canvas id = "animation" width="1130" height="222"></canvas>
and what I want to do, is to add 3 images (+1 more which is the background), and during each second I want to have 1 image shown and the other 2 hidden.
What I have now is:
var canvas = document.getElementById('animation');
context = canvas.getContext('2d');
background = new Image();
background.src = 'images/background.png';
background.onload = function(){
context.drawImage(background, 0, 0);
}
var image1 = new Image();
image1.src = 'images/image1.png';
image1.onload = function(){
context.drawImage(image1, 895, 61);
}
var image2 = new Image();
image2.src = 'images/image2.png';
image2.onload = function(){
context.drawImage(image2, 895, 61);
}
var image3 = new Image();
image3.src = 'images/image3.png';
image3.onload = function(){
context.drawImage(image3, 895, 61);
}
image1.style.visibility = "visible";
image2.style.visibility = "hidden";
image3.style.visibility = "hidden";
setTimeout(function(){
image1.style.visibility = "hidden";
image2.style.visibility = "visible";
image3.style.visibility = "hidden";
}, 1000);
setTimeout(function(){
image1.style.visibility = "hidden";
image3.style.visibility = "visible";
image2.style.visibility = "hidden";
}, 2000);
setTimeout(function(){
image3.style.visibility = "hidden";
image1.style.visibility = "visible";
image2.style.visibility = "hidden";
}, 3000);
however it does not work. All of them appear on the screen
You are trying to mix two different things here: canvas and CSS.
The canvas works like (surprise!) a canvas: that means that once you draw something there it will stay there until you draw something else over it. Therefore, changing the css of the images on memory will have no effect.
You have two alternatives: the DOM route, just insert the images in the DOM without the canvas and you will be able to change their style, or the Canvas route, calling to context.drawImage INSIDE various setTimeout, so you draw a new image each second.
I have an issue I'm having a hard time believing... It seems that when I draw to a dynamically created canvas in Firefox it wont render the first time that source is run... It seems to happen the first time the JavaScript in question is run either by modifying the source or visiting the link for the first time. Here are some repro steps:
1) open a brand new instance of Firefox. visit the jsFiddle below.
2) see nothing
3) open a new tab in Firefox. visit the jsFiddle below.
4) see the result (10 colored squares)
Doing this in Chrome will result in seeing the result at both step 2 and step 4.
https://jsfiddle.net/sk873txv/1/
html
<body>
<div id="a">
</div>
</body>
js
$(document).ready(function(){
var make_canvas = function(i) {
var $canvas = $('<canvas>').appendTo($('#a'));
$canvas.attr('width', '100px');
$canvas.attr('height', '100px');
var canvas = $canvas[0];
var ctx = canvas.getContext('2d');
return ctx;
};
var draw = function(ctx) {
var image = new Image();
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkEAIAAACvEN5AAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAABa0lEQVR42u3cMU4CARRF0SeyWl0P7FaxoKbBuRrNOZUJCU7xcv9UvGzb7Xa6btvrddse/f2dT0+Xg77noOd58r9c/tTTPvr08hPPc962z7fBoc7b9mFYHEyxSCgWCcUioVgkDIuEU0hCsUgoFgnFImFYJJxCEopFQrFIKBaJe7Hef/sx+G8Ui4RhkfDyTkKxSCgWCcUiYVgknEISikVCsUgoFgnFIqFYJAyLhFNIQrFIKBYJxSJhWCScQhKKRUKxSCgWCcMi4RSSUCwSikVCsUgoFgnFImFYJJxCEvdi+eE1DqZYJLxjkTAsEk4hCcUioVgkFIuEYpFQLBKGRcIpJKFYJBSLhGKRMCwSTiEJxSKhWCQUi4RhkXAKSSgWCcUioVgkFIuEYpEwLBJOIQnFIqFYJBSLhGGRuJ9CP7zGwRSLhJd3EopFQrFIKBYJwyLhFJJQLBKKRUKxSBgWCaeQhGKRUCwSikVCsUh8ARsPyYz6AmddAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDExLTA0LTA3VDIxOjM2OjAyKzEwOjAwezv9bwAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxMS0wNC0wN1QyMTozNjowMisxMDowMApmRdMAAAA2dEVYdFBORzpiS0dEAGNodW5rIHdhcyBmb3VuZCAoc2VlIEJhY2tncm91bmQgY29sb3IsIGFib3ZlKbpeXNkAAAAVdEVYdFBORzpJSERSLmJpdF9kZXB0aAAxNqc4FdcAAAAVdEVYdFBORzpJSERSLmNvbG9yX3R5cGUAMgEnYzIAAAAbdEVYdFBORzpJSERSLmludGVybGFjZV9tZXRob2QAMPs7B4wAAAAedEVYdFBORzpJSERSLndpZHRoLGhlaWdodAAxMDAsIDEwMNtVy6kAAAAkdEVYdFBORzpwSFlzAHhfcmVzPTcyLCB5X3Jlcz03MiwgdW5pdHM9MKQw/n0AAAArdEVYdFBORzp0ZXh0ADIgdEVYdC96VFh0L2lUWHQgY2h1bmtzIHdlcmUgZm91bmRcYYD5AAAAAElFTkSuQmCC";
ctx.drawImage(image, 0, 0);
};
for(var i = 0; i < 10; i++)
{
draw(make_canvas(i));
}
});
You should wait for the load event to fire on the image, before drawing it to a canvas. Even though the image data is embedded as a data URI, there is no guarantee the image will be rendered and ready to draw the instant you set the src. Waiting for the load event will ensure the image is ready.
Working Example (JSFiddle):
$(document).ready(function(){
var make_canvas = function(i) {
var $canvas = $('<canvas>').appendTo($('#a'));
$canvas.attr('width', '100px');
$canvas.attr('height', '100px');
var canvas = $canvas[0];
var ctx = canvas.getContext('2d');
return ctx;
};
var draw = function(ctx) {
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkEAIAAACvEN5AA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dlcmUgZm91bmRcYYD5AAAAAElFTkSuQmCC";
};
for(var i = 0; i < 10; i++)
{
draw(make_canvas(i));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="a">
</div>
</body>
First off see this Fiddle
I want to create a canvas on the fly and append it to a particular DIV and draw an inline svg onto the canvas. But does not work as expected.
var randn = '1';
function createme(){
alert("completed 0");
var crCavs = $('<canvas />',{ id : 'mycanvs'+randn })
$('#album').append(crCavs);
alert("completed 1");
var svg2 =document.getElementById('sVgsource'+randn).outerHTML,
vms =document.getElementById('mycanvs'+randn), // target canvas
ctx2 =vms.getContext('2d');
//callback
svgToImage(svg2, function(img2){
vms.width =$('#sVgsource'+randn).width();
vms.height =$('#sVgsource'+randn).height();
alert("completed 3");
ctx2.drawImage(img2, 30, 40);
alert("completed 4");
}
function svgToImage(svg2, callback) {
var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
img2 = new Image;
//invoke callback
callback(img2);
img2.src = nurl;
alert("completed 2");
}
}
createme();
You are missing an end-parenthesis for the svgToImage() function:
svgToImage(svg2, function(img2) {
vms.width = img2.width;
vms.height = img2.height;
alert("completed 3");
ctx2.drawImage(img2, 0, 0);
alert("completed 4");
}); // <-- here
There are also some other issues:
Just reuse the canvas element:
var canvCrtrWrp = $('<canvas />',{ id : 'mycanvs'+randn })
...
var vms = canvCrtrWrp[0]; // index 0 is the actual canvas element
You could also use the width from the produced image on the canvas:
svgToImage(svg2, function(img2) {
vms.width = img2.width;
vms.height = img2.height;
...
Remember to use the onload handler for image (it was removed from the original code).If not an image element is passed back without any actual image data (need some time to load, decode etc.):
function svgToImage(svg2, callback) {
var nurl = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg2),
img2 = new Image;
img2.onload = function() {
callback(this);
}
...
etc.
Updated fiddle.