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.
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.
I am Alex and this is my first stack overflow question.
I have the below script.
-This script gets images from an api.
-For each image received from the api, an element is created
-for each image, a class attribute is created
-for each image, an id attribute is created.
-for each image, a element is created. For each of the , I dynamically append an onclick event. each onclick is associated with its own function.
the anchor1,2,3,4 and 5 function are made so each time a user clicks a selected image, that image is then place into a canvas. When that is done, the color thief js kicks in and displays the color palette of the image selected.
All of that works perfectly.
What I would like to do is instead of having a function for each image, is to have 1 function that would place the image clicked into the canvas.
Basically i think my code can be made less redundant.
// search the collection using a JSON call
function search(query) {
return $.getJSON("https://www.rijksmuseum.nl/api/en/collection?q=Q&key=r4nzV2tL&imgonly=True&ps=5&format=json".replace("Q", query));
}
var searchBtn = document.getElementById("search");
searchBtn.addEventListener("click", doSearch);
var resultD = document.getElementById("result");
var searchField = document.getElementById("query");
//search function starts here
function doSearch() {
$("#result").show(); // result div to show when making new search
resultD.innerHTML = "";
var searchString = searchField.value;
if (searchString !== "") {
search(searchString).done(function(data) {
for (var artObj in data.artObjects) {
var rImg = document.createElement("img"); // create the image
rImg.setAttribute("crossOrigin", "Anonymous"); //needed so I can actually copy the image for later use
rImg.setAttribute("class", "imageClass"); //needed so I can actually copy the image for later use
var link = document.createElement("a"); // create the link
link.setAttribute('href', '#'); // set link path
// link.href = "www.example.com"; //can be done this way too
rImg.src = data.artObjects[artObj].webImage.url; // the source of the image element is the url from rijks api
link.appendChild(rImg); // append image to link
resultD.appendChild(link); // append link with image to div
resultD.innerHTML += data.artObjects[artObj].title; // this is the title from rijks api
$("#result img").each(function (i, image){ //for each image create a different id
image.id = "image" + (i + 1);
});
$("#result a").each(function (i, anchor){ //for each anchor create a different id
anchor.id = "anchor" + (i + 1);
anchor.setAttribute('onclick', "anchor" + (i + 1)+'();return false;'); // set link path
//return false needed so to avoid page jump
});
resultD.innerHTML += "<br> <br> <br> <br>";
}
});
}
}//search function ends here
//for each image create size matching canvas
function anchor1(){
var c=document.getElementById("drawing1");
var ctx=c.getContext("2d");
var img=document.getElementById("image1");
c.height = img.height ;
c.width = img.width ;
ctx.drawImage(img,0,0,c.width, c.height);
$("#result").hide();
setTimeout(function() { //timeout for image load to canvas - start
var colorThief = new ColorThief();
var color = colorThief.getPalette(img, 18);
var newHTML = $.map(color, function(value) {
return('<div style="background-color:rgb(' + value.join(', ') + ')"> </div>'+'<br>');
});
$("#colors").html(newHTML.join(''));
}, 500); //timeout for image load to canvas - ends
}
function anchor2(){
var c=document.getElementById("drawing1");
var ctx=c.getContext("2d");
var img=document.getElementById("image2");
c.height = img.height ;
c.width = img.width ;
ctx.drawImage(img,0,0,c.width, c.height);
$("#result").hide();
setTimeout(function() { //timeout for image load to canvas - start
var colorThief = new ColorThief();
var color = colorThief.getPalette(img, 18);
var newHTML = $.map(color, function(value) {
return('<div style="background-color:rgb(' + value.join(', ') + ')"> </div>'+'<br>');
});
$("#colors").html(newHTML.join(''));
}, 500); //timeout for image load to canvas - ends
}
function anchor3(){
var c=document.getElementById("drawing1");
var ctx=c.getContext("2d");
var img=document.getElementById("image3");
c.height = img.height ;
c.width = img.width ;
ctx.drawImage(img,0,0,c.width, c.height);
$("#result").hide();
setTimeout(function() { //timeout for image load to canvas - start
var colorThief = new ColorThief();
var color = colorThief.getPalette(img, 18);
var newHTML = $.map(color, function(value) {
return('<div style="background-color:rgb(' + value.join(', ') + ')"> </div>'+'<br>');
});
$("#colors").html(newHTML.join(''));
}, 500); //timeout for image load to canvas - ends
}
function anchor4(){
var c=document.getElementById("drawing1");
var ctx=c.getContext("2d");
var img=document.getElementById("image4");
c.height = img.height ;
c.width = img.width ;
ctx.drawImage(img,0,0,c.width, c.height);
$("#result").hide();
setTimeout(function() { //timeout for image load to canvas - start
var colorThief = new ColorThief();
var color = colorThief.getPalette(img, 18);
var newHTML = $.map(color, function(value) {
return('<div style="background-color:rgb(' + value.join(', ') + ')"> </div>'+'<br>');
});
$("#colors").html(newHTML.join(''));
}, 500); //timeout for image load to canvas - ends
}
function anchor5(){
var c=document.getElementById("drawing1");
var ctx=c.getContext("2d");
var img=document.getElementById("image5");
c.height = img.height ;
c.width = img.width ;
ctx.drawImage(img,0,0,c.width, c.height);
$("#result").hide();
setTimeout(function() { //timeout for image load to canvas - start
var colorThief = new ColorThief();
var color = colorThief.getPalette(img, 18);
var newHTML = $.map(color, function(value) {
return('<div style="background-color:rgb(' + value.join(', ') + ')"> </div>'+'<br>');
});
$("#colors").html(newHTML.join(''));
}, 500); //timeout for image load to canvas - ends
}
You want to utilize the .on event with jquery which allows you to deal with dynamic data which is basically what you are dealing with.
You are generating different <a> links with an individual id to call your different functions like (anchor1, anchor2...) with $("#result a").each(function (i, anchor){ //for each anchor create a different id anchor.id = "anchor" + (i + 1);
Instead of generating a different id for each <a> just give them the same value, but make it a class and not a id. Id's should always be unique and never repeat, classes can be repeated. For instance <a class="anchor"><...</a>
Then when you want to deal with the data from that particular record/image you would call it as such.
$(document).on('click','.anchor', function () {
});
So here is a working example you can start with.
<a class="anchor" data-id="1">...</a>
$(document).on('click','.anchor', function () {
var anchor_id = $(this).attr('data-id').val();
var c=document.getElementById("drawing1");
var ctx=c.getContext("2d");
var img=document.getElementById("image"+anchor_id); //this will attach the id for that image here
c.height = img.height ;
c.width = img.width ;
ctx.drawImage(img,0,0,c.width, c.height);
$("#result").hide();
setTimeout(function() { //timeout for image load to canvas - start
var colorThief = new ColorThief();
var color = colorThief.getPalette(img, 18);
var newHTML = $.map(color, function(value) {
return('<div style="background-color:rgb(' + value.join(', ') + ')"> </div>'+'<br>');
});
$("#colors").html(newHTML.join(''));
}, 500); //timeout for image load to canvas - ends
});
http://api.jquery.com/on/
https://learn.jquery.com/events/handling-events/
http://html-tuts.com/jquery-this-selector/
I have been trying to draw a tile-like map to the canvas, although if i try to draw the same sprite twice, it will only render the final call of drawImage. Here is my code if it helps :
window.onload = function(){
function get(id){
return document.getElementById(id);
}
var canvas = get("canvas");
ctx = canvas.getContext("2d");
canvas.width = 160;
canvas.height = 160;
grass = new Image();
water = new Image();
grass.src = "res/Grass.png";
water.src = "res/Water.png";
path = {
draw: function(image,X,Y){
X = (X*32)-32;
Y = (Y*32)-32;
image.onload = function(){
ctx.drawImage(image,X,Y);
}
},
}
path.draw(water,2,2);
path.draw(grass,1,2);
path.draw(grass,1,1);
path.draw(water,2,1);
}
You're overwriting onload on the image next time you call it.
Think of it this way:
var image = {
onload: null
};
// Wait for the image to "load"
// Remember, onload is asynchronous so it won't be called until the rest of
// your code is done and the image is loaded
setTimeout(function() {
image.onload();
}, 500);
image.onload = function() {
console.log('I will never be called');
};
image.onload = function() {
console.log('I overwrite the previous one');
};
Instead, you might try waiting for your images to load then do the rest of your logic.
var numOfImagesLoading = 0;
var firstImage = new Image();
var secondImage = new Image();
// This is called when an image finishes loading
function onLoad() {
numOfImagesLoading -= 1;
if (numOfImagesLoading === 0) {
doStuff();
}
}
function doStuff() {
// This is where you can use your images
document.body.appendChild(firstImage);
document.body.appendChild(secondImage);
}
firstImage.src = 'http://placehold.it/100x100';
firstImage.onload = onLoad;
numOfImagesLoading += 1;
secondImage.src = 'http://placehold.it/200x200';
secondImage.onload = onLoad;
numOfImagesLoading += 1;
UPDATED
I have an HTML code below:
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
I have a function below:
var Context;
function onSign(canvas){
var ctx = document.getElementById(canvas).getContext('2d');
SigWebSetDisplayTarget(ctx);
tmr = setInterval(SigWebRefresh, 50);
}
function SigWebSetDisplayTarget( obj ){
Context = obj;
}
I called the function OnSign twice with different canvas id parameters.
OnSign('canvas1');
OnSign('canvas2');
Below is the SigWebRefresh function that is repeatedly called for a reason.
function SigWebRefresh(){
xhr2 = new XMLHttpRequest();
requests.push(xhr2);
xhr2.open("GET", baseUri + "SigImage/0", true );
xhr2.responseType = "blob"
xhr2.onload = function (){
var img = new Image();
img.src = 'image.jpg';
img.onload = function (){
Ctx.drawImage(img, 0, 0);
revokeBlobURL( img.src );
img = null;
}
}
xhr2.send(null);
}
After that, I noticed that the two canvas was being updated and the image is loaded to the 2 canvas. Why is it? I have to load the image, only to the last canvas I supplied with the function OnSign. Where am I missing?
var Context; is declared in global scope
OnSign('canvas1');
OnSign('canvas2');
Doing so you are assigning value of canvas number two.
Update: http://jsfiddle.net/bmynvtLd/2/
This is what you desired to update both contexts? if yes this is how you pass the parameter to setInterval function: setInterval(function() {SigWebRefresh(ctx)}, 300);
running example:
var images = ['http://img09.deviantart.net/6d02/i/2015/284/0/b/beginning_autumn_by_weissglut-d9cssxw.jpg', 'http://orig06.deviantart.net/063c/f/2013/105/3/6/free_crystal_icons_by_aha_soft_icons-d61tfi1.png', 'http://img15.deviantart.net/b126/i/2015/118/c/1/this_small_tree_by_weissglut-d8re8q7.jpg', 'http://img00.deviantart.net/84f8/i/2015/284/d/f/nuclear_light_by_noro8-d9cs4u6.jpg'];
function OnSign(canvas){
var ctx = document.getElementById(canvas).getContext('2d');
tmr = setInterval(function() {SigWebRefresh(ctx)}, 300);
}
OnSign('canvas1');
OnSign('canvas2');
var index = 0;
function MyIndex()
{
// console.log(index);
index = images.length == index ? 0 : index+1;
return images[index];
}
function SigWebRefresh(Context){
var img = new Image();
img.src = MyIndex();
img.onload = function (){
Context.drawImage(img, 0, 0);
img = null;
}
}
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.