Method for saving an HTML canvas image - image

I’d like to concatenate two or three images (bottom of one to top of next) , and save that image for use on another page (shopping cart page) as a thumbnail. I've been looking into using either the HTML5 cache manifest, or the canvas.toDataURL() method. Which is more suited to this purpose?
I've written code for the toDataURL() method below:
<div style="width: 80px;">
<img id="imageA" src="imageA.jpg" alt="imageA"
width="70" height="400" >
<img id="imageB" src="imageB.jpg" alt="imageB"
width="70">
<canvas id="canvas1"></canvas>
<script type="text/javascript">
var img1 = document.getElementById("imageA");
var img2 = document.getElementById("imageB");
var canvas1 = document.getElementById("canvas1");
var context1 = canvas1.getContext("2d");
canvas1.width = "70";
canvas1.height = "470";
context1.globalAlpha = 1.0;
var combinedImage = ctx.getImageData(0, 0, 70, 470);
var imgURL = canvas.toDataURL("image/png");
</script>
</div>

A cache manifest has no relevance here unless you want to have the images available when off-line, but has no effect when it comes to merging images.
The code shown is not actually drawing the images into the canvas and when you call getImageData() you will only get an empty pixel buffer which is not useful here.
Try something like this instead (JavaScript part only):
var img1 = document.getElementById("imageA");
var img2 = document.getElementById("imageB");
var canvas1 = document.getElementById("canvas1");
var context1 = canvas1.getContext("2d");
canvas1.width = 70; /// use numbers instead of strings here
canvas1.height = img1.height + img2.height;
/// draw the images onto canvas
context1.drawImage(img1, 0, 0);
context1.drawImage(img2, 0, img1.height);
var imgURL = canvas1.toDataURL(); /// defaults to PNG
Now your imgURL will contain the concatenated images as a PNG provided CORS requirements are fulfilled (ie. they are on the same server). You should also see the on-screen canvas with the two images embedded.
Hope this helps.

Related

How to use x2 canvas elements and rendering paper.js on img capture of html5 video to base64

Still very much a newbie to coding, so please be gentle :)
I'm hoping someone might be able to help how to use Paper.js on a second canvas after the first one has been executed?
I'm trying to use x2 canvas elements:
Canvas 1 - to capture a html5 video image still and convert to base64 (tick :-) = done)
Canvas 2 - Use the base64 image and perform the 'Working with Rasters to find the colors of pixels' and convert to circle paths (boo = fail :-( )
Something like this:
The code:
<script src="https://cdn.jsdelivr.net/npm/hls.js#latest"></script>
<video id="video" preload="auto" muted="" playsinline="" width="580" src="blob:https://www.georgefisher.co.uk/78e3a45c-ae07-4ea5-af56-45a5ed9cf1b0"></video>
<script>
var video = document.getElementById('video');
var videoSrc = 'https://camsecure.co/HLS/georgefisher.m3u8';
if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(videoSrc);
hls.attachMedia(video);
}
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = videoSrc;
}
video.play()
</script>
<br>
<button onclick="capture()">Capture</button>
<br>
<canvas id="canvas" style="overflow:auto">
</canvas>
<canvas id="canvas2" resize>
<img src="" id="myImg"/></canvas>
var resultb64="";
function capture() {
var canvas = document.getElementById('canvas');
var video = document.getElementById('video');
canvas.width = video.videoWidth/4;
canvas.height = video.videoHeight/4;
canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth/4, video.videoHeight/4);
resultb64=canvas.toDataURL();
document.querySelector("#myImg").src = canvas.toDataURL();
}
/*Paper JS Setup for working in CodePen */
/* ====================== *
* 0. Initiate Canvas *
* ====================== */
// expose paperjs classes into global scope
paper.install(window);
// Only executed our code once the DOM is ready.
window.onload = function() {
// bind paper to the canvas
paper.setup('canvas2');
// paper.activate();
// Get a reference to the canvas object
var canvas = document.getElementById('canvas2');
var ctx = canvas.getContext('2d');
// console.log(ctx, image);
// ctx.drawImage(image, 0, 0);
// return;
// }
// Create a raster item using the image id='' tag
var image = document.querySelector('img');
var raster = new Raster(image);
// Hide the raster:
raster.visible = false;
// The size of our grid cells:
var gridSize = 15;
// Space the cells by 120%:
var spacing = 1
;
// As the web is asynchronous, we need to wait for the raster to load before we can perform any operation on its pixels.
raster.onLoad = function() {
// Since the example image we're using is much too large, and therefore has way too many pixels, lets downsize it to 40 pixels wide and 30 pixels high:
raster.size = new Size(40, 30);
for (var y = 0; y < raster.height; y++) {
for(var x = 0; x < raster.width; x++) {
// Get the color of the pixel:
var color = raster.getPixel(x, y);
// Create a circle shaped path:
var path = new Path.Circle({
center: new Point(x, y).multiply(gridSize),
radius: gridSize / 2 / spacing,
});
// Set the fill color of the path to the color
// of the pixel:
path.fillColor = color;
}
}
// Move the active layer to the center of the view, so all the created paths in it appear centered.
project.activeLayer.position = view.center;
}
}
I've tried giving the second canvas a different Id="canvas2" and referencing that, which I can see in the console. However, nothing appears in the second canvas and the paper.js script doesn't seem to execute, can someone help me understand why?
Please see also see link to the fiddle below:
https://jsfiddle.net/jmnes/o4Lpkfs6/1/
Alternatives method.
You don't need to capture the video, you don't need to capture the pixels using paper.js and raster. You don't need to find the color of each circle and draw it.
All these methods are slow, complex, and power hungry.
You can create a mask and mask out the circles, with the colors drawn from a smaller canvas with a res that matches the number off circles.
How to
Add one (main canvas) canvas to the DOM. This will display the result
Create 2 offscreen canvas.
One (color canvas) has the same resolution as the circles you want to display. Eg if you have 30 by 40 circle the canvas res should be 30 by 40
One (mask canvas) is the circle mask. It is the same resolution as the main canvas. Draw the circles all in one color on this canvas.
Then rendering once a frame
Draw the video on the color canvas to fit.
Turn off smoothing on the main canvas eg ctxMain.imageSmoothingEnabled = false
Draw the color canvas onto the main canvas to fit.
This will draw a color square at each circle position. ctx.drawImage(colorCanvas, 0, 0, mainCanvas.width, mainCanvas.height)
Set composite operation "destination-in" eg ctxMain.globalCompositeOperation = "destination-in"
Draw the mask canvas (canvas with circles on it) onto the main canvas. This will remove pixels outside each circle.
Restore default composite operation for the main canvas ctxMain.globalCompositeOperation = "source-over"
All done for a real-time FX on almost any device.
The above methods is the fastest way to render the effect you are after using the 2D API

How to display an image offline using Famo.us

How can you display an image that can be used offline using Famo.us?
A Famo.us Image surface sets it's content based on an image URL. However, when offline, this URL will not work. I have tried using an HTTP request and converting the buffer to a Blob and then creating a URI for the Blob:
// bytes = request.buffer of HTTP request
// Make a Blob from the bytes
var blob = new Blob([bytes], {type: 'image/jpg'});
// Use createObjectURL to make a URL for the blob
imageURL = URL.createObjectURL(blob);
//Use Famo.us image surface API to display the image (http://famo.us/docs/api/latest/surfaces/ImageSurface)
imageSurface.setContent(imageURL);
This does not throw any warning or errors but displays a broken image. Any suggestions? I want to display an image even when I am offline, but when I reconnect I will request for the newest image uploaded.
ImageSurface in Famo.us can take a url to the image or the base-64 encoded data.
Using Blob:
Use the file reader to readAsDataURL
var reader = new FileReader();
reader.onloadend = function () {
imageURL = reader.result;
}
reader.readAsDataURL(blob);
Using Canvas:
There are plenty of ways to get the encoded base-64 data. Canvas has another way to get this string for you.
Example jsBin Here
Using the example snippet below, you can see how you can use Canvas.toDataURL.
var image = new Image();
image.crossOrigin = 'anonymous'; // only needed for CORS, not needed for same domain.
// create an empty canvas element
var canvas = document.createElement("canvas");
var canvasContext = canvas.getContext("2d");
image.onload = function () {
//Set canvas size is same as the picture
canvas.width = image.width;
canvas.height = image.height;
// draw image into canvas element
canvasContext.drawImage(image, 0, 0, image.width, image.height);
// get canvas contents as a data URL (returns png format by default)
imageURL = canvas.toDataURL();
};
image.src = 'http://code.famo.us/assets/famous_logo.png';

How to get base64 image data without call canvas toDataURL?

I'm on a project which requires to support ie9 or ie10.
I'm using d3.js for data visualization.
Now I need to provide a function to export the chart as pdf.
I have been investigate into possible solutions. It seems that canvas + jsPdf is the way to go, below is some code I write.
But the problem is that when toDataURL gets called, it will cause security errors on IE9 and IE10. So I'm wondering if there's some work around to get base64 image data without using canvas since jsPdf only needs base64 image data???
createObjectURL to the root svg element
svgElement = $('svg').get(0);
serializer = new XMLSerializer();
str = serializer.serializeToString(svgElement);
DOMURL = window.URL || window.webkitURL || window;
url = DOMURL.createObjectURL(new Blob([str], {type: 'image/svg+xml;charset=utf-8'}));
draw an image using canvas
img = new Image();
img.onload = function(){
ctx.drawImage(img, 0, 0);
imgData = $canvas.get(0).toDataURL("image/jpeg");
DOMURL.revokeObjectURL(url);
pdf = new jsPDF('landscape', 'pt', 1000, 800);
pdf.addImage(imgData, 'JPEG', 0, 0);
pdf.save('download.pdf');
};
img.src = url;
I finally find the solution which is to use an open source project: canvg

Positioning an HTML5 Canvas Element

I am completely new to HTML5 and have been reading about it for the past few days mainly because I wanted to create a rotating image to put in a <div>. I found a code that does exactly what I want, but it throws the canvas on to the bottom left corner of my page (I'm not sure why, but I think it has something to do with the very first line of the code below). I'm not sure how to adapt the code to a element so that I can put it where I want. From looking at other people's scripts and trying to emulate them, I know you're supposed to do this sort of thing to hold the canvas "<canvas width="100" height="100" id="pageCanvas"></canvas>," but I don't know how to name the below code in order to do that. I greatly appreciate any help anyone can offer me - thank you so much for reading! :)
<script>
window.addEventListener("load", init);
var counter = 0,
logoImage = new Image(),
TO_RADIANS = Math.PI/180;
logoImage.src = 'IMG URL';
var canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext('2d');
document.body.appendChild(canvas);
function init(){
setInterval(loop, 1000/30);
}
function loop() {
context.clearRect(0,0,canvas.width, canvas.height);
drawRotatedImage(logoImage,100,100,counter);
drawRotatedImage(logoImage,300,100,counter+90);
drawRotatedImage(logoImage,500,100,counter+180);
counter+=2;
}
function drawRotatedImage(image, x, y, angle) {
// save the current co-ordinate system
// before we screw with it
context.save();
// move to the middle of where we want to draw our image
context.translate(x, y);
// rotate around that point, converting our
// angle from degrees to radians
context.rotate(angle * TO_RADIANS);
// draw it up and to the left by half the width
// and height of the image
context.drawImage(image, -(image.width/2), -(image.height/2));
// and restore the co-ords to how they were when we began
context.restore();
}
</script>
Create a canvas element in your HTML code so you can place it exactly where you want (with html + css) :
<canvas id='canvas' height='100' width='100'> Your browser does not support HTML5 canvas </canvas>
And replace this javascript code :
var canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext('2d');
document.body.appendChild(canvas);
by this one :
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

Can we get the real image size through the canvas?

In image tag, if we don't supply width and height property, we will get nothing when retrieving the width and the height of the image. I am using the canvas element to load an image and scale it proportionally. In order to do this, I have to get the actual image size. Is it possible to do that in html 5?
The HTMLImageElement has two properties for this, naturalWidth and naturalHeight. Use those.
As in:
var img = new Image();
img.addEventListener('load', function() {
// once the image is loaded:
var width = img.naturalWidth; // this will be 300
var height = img.naturalHeight; // this will be 400
someContext.drawImage(img, 0, 0, width, height);
}, false);
img.src = 'http://placekitten.com/300/400'; // grab a 300x400 image from placekitten
It is wise to set source only after the event listener is defined, see Phrogz's exploration on that here: Should setting an image src to data URL be available immediately?
You cannot retrieve width/height before image has been loaded.
Try something like:
// create new Image or get it right from DOM,
// var img = document.getElementById("myImage");
var img = new Image();
img.onload = function() {
// this.width contains image width
// this.height contains image height
}
img.src = "image.png";
Anyhow onload will not fire if image has been loaded before script execution. Eventually you can embed script in html <img src="test.jpg" onload="something()">
if I understand you correctly, you can use the getComputedStyle method.
var object = document.getElementById(el);
var computedHeight = document.defaultView.getComputedStyle(object, "").getPropertyValue("width");
Not fully understood your question.
But you can use javascript to get the width and height of the image.
and then pass it into
/ Five arguments: the element, destination (x,y) coordinates, and destination
// width and height (if you want to resize the source image).
context.drawImage(img_elem, dx, dy, dw, dh);
while drawing image on canvas.
or check this if it helps
http://jsfiddle.net/jjUHs/

Resources