Using Canvas and Drawimage in functions with video - javascript

I am using the HTML5 canvas and DrawImage functions to display low rate video. tnt gave excellent advice to get this project off the ground: Trying to use Canvas and DrawImage to display low-rate video at 90 degrees
While tnt's solution worked fine when the camera and angle are known at load time by using onload functions, I need to be able to turn the video off and on between several cameras and change other parameters. To handle that, a number of individual functions are needed, but I haven't been able to first do a setInterval on a camera and then pass the constantly changing image to DrawImage. 'cam_1.jpg' is the video in the example below. The functions shown in body onload below will also have to be called by other routines during runtime. Any advice will be appreciated.
var cam = null;
var c = null;
var ctx = null;
var ra = 0;
function init() {
cam = new Image;
c = document.getElementsByTagName('canvas')[0];
ctx = c.getContext('2d');
}
function draw(cam) {
ctx.save();
ctx.clearRect( 0, 0, 240, 320 );
ctx.translate( 240, 0);
ctx.rotate(1.57);
ctx.drawImage(cam, 0, 0 );
ctx.restore();
}
function inter() {
setInterval(function(){cam.src = 'cam_1.jpg?uniq='+Math.random();},500);
}
</script></head><body onload = "init(), draw(cam), inter()" >
Thank you.

I suggest you use an object array; something like this:
var cams = []; // an array to hold you cams!
function addcam() {
this.image = new Image;
this.setting1 = 0;
this.settingn = 0;
}
cams[1] = addcam();
cams[1].image.src = "cam1.jpg";
cams[1].setting1 = 2;
setInterval(function(){cam.src = '+cams[1].image.src+'?uniq='+Math.random();},500);

#tnt, Are you suggesting the following? Thank you:
var cams = []; // an array to hold you cams!
function addcam() {
this.image = new Image;
this.setting1 = 0;
this.settingn = 0;
}
function draw(camnum){
cams[1] = addcam();
cams[1].image.src = "cam_1.jpg";
cams[1].setting1 = 2;
cam = new Image;
c = document.getElementsByTagName('canvas')[0];
ctx = c.getContext('2d');
}
function inter() {
setInterval(function(){'cam.src = ' +cams[1].image.src+ '?uniq='+Math.random();},500);
}
function draw(cam) {
ctx.save();
ctx.clearRect( 0, 0, 240, 320 );
ctx.translate( 240, 0);
ctx.rotate( 1.57);
ctx.drawImage(this, 0, 0 );
ctx.restore();
}
</script></head><body onload = "draw(cam), inter()" >

Related

How can i save an image in my computer that has been filtered with CSS [duplicate]

I'm building a new website that will let users apply filters to images (just like Instagram). I will use -webkit-filter for that.
The user must be able to save the filtered image. There is any way I can do that using JavaScript?
You can't save images directly, but you can render them in Canvas, then save from there.
See: Save HTML5 canvas with images as an image
There is no direct/straight forward method to export an image with CSS Filter.
Follow the below steps for Saving/Exporting an Image with -webkit-filter applied on it:
1. Render the image to a canvas:
var canvas = document.createElement('canvas');
canvas.id="canvasPhoto";
canvas.width = imageContaainer.width;
canvas.height = imageContaainer.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(imageContaainer, 0, 0, canvas.width, canvas.height);
Get the ImageData from canvas and apply the filter. Eg: I will apply grayscale filter to the ImageData below:
function grayscale(ctx) {
var pixels = ctx.getImageData(0,0,canvas.width, canvas.height);
var d = pixels.data;
for (var i=0; i<d.length; i+=4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
var v = 0.2126*r + 0.7152*g + 0.0722*b;
d[i] = d[i+1] = d[i+2] = v
}
context.putImageData(pixels, 0, 0);
}
Add an event and use the below code to trigger download
function download(canvas) {
var data = canvas.toDataURL("image/png");
if (!window.open(data))
{
document.location.href = data;
}
}

How to change window level of an image on canvas using javascript

I have an image on canvas or a set of images that i draw on the canvas. I can draw them fine but I want to change the window level of the image on canvas by dragging the mouse over it. I've seen a lot of external javascript api's but they're quite huge and i don't want to use them for this purpose.
here's my JSFIDDLE that is basically drawing an image on the canvas
this is how my code looks
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
// Create an image element
var img = document.createElement('IMG');
// When the image is loaded, draw it
img.onload = function () {
ctx.drawImage(img, 0, 0);
}
// Specify the src to load the image
img.src = "http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/sample5_l.jpg";
i need something with basic JS or JQuery. it would be great if you can point me in the right direction using a sample code.
Thanks in advance.
If you want to use JavaScript, try something like:
<script>
var c = document.getElementById("drawingboard");
var ctx = c.getContext("2d");
var mouseDown = 0;
document.body.ontouchstart = function() {
mouseDown+=1;
}
document.body.ontouchend = function() {
mouseDown-=1;
}
function draw(event){
ctx.color='gold';
ctx.fillStyle = "lime";
ctx.drawImage(img,event.clientX,event.clientY);}
</script>
This is what I gained after some research:
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const rangeMin = level - window / 2;
const rangeMax = level + window / 2;
const totalSize = canvas.width * canvas.height;
for (let idx = 0; idx < totalSize; idx++) {
if (imageData.data[idx] < rangeMin) {
imageData.data[idx] = 0;
} else if (imageData.data[idx] > rangeMax) {
imageData.data[idx] = 255;
}
}
ctx.putImageData(imageData, 0, 0);

getImageData() returning all zeros

I'm trying to output the pixel values from an image. The image is loading correctly; another answer on here suggested that the browswer is trying to read the pixels before the image is finished loading, but I can see that it's loaded by the time the alert() fires.
function initContext(canvasID, contextType)
{
var canvas = document.getElementById(canvasID);
var context = canvas.getContext(contextType);
return context;
}
function loadImage(imageSource, context)
{
var imageObj = new Image();
imageObj.onload = function()
{
context.drawImage(imageObj, 0, 0);
};
imageObj.src = imageSource;
return imageObj;
}
function readImage(imageData)
{
console.log();
console.log(imageData.data[0]);
}
var context = initContext('canvas','2d');
var imageObj = loadImage('images/color-test.png',context);
var imageData = context.getImageData(0,0,10,10);
alert();
readImage(imageData);
Image.onload() is called asynchronously when the image has been loaded. That can happen after your current code calls context.getImageData().
The following code should work:
function initContext(canvasID, contextType)
{
var canvas = document.getElementById(canvasID);
var context = canvas.getContext(contextType);
return context;
}
function loadImage(imageSource, context)
{
var imageObj = new Image();
imageObj.onload = function()
{
context.drawImage(imageObj, 0, 0);
var imageData = context.getImageData(0,0,10,10);
readImage(imageData);
};
imageObj.src = imageSource;
return imageObj;
}
function readImage(imageData)
{
console.log();
console.log(imageData.data[0]);
}
var context = initContext('canvas','2d');
var imageObj = loadImage('images/color-test.png',context);
If you want to access the imageData value outside of loadImage(), you have 2 basic choices:
Store the imageData in a variable that is declared outside the function. In this case, the value will be unset until your onload() is called, so the outside code would have to test it for reasonableness before calling readImage(imageData).
Have the outside code register a callback function, and have your onload() call that function with the imageData value.
It is also possible you are evaluating a portion of an image that is transparent. I had this issue while scanning a PNG.
Share a situation I encountered when I used a loop to request multiple images at the same time and get their pixels respectively. Then I encountered this problem.
//my code looks like this
for(let i = 0; i < urls.length; ++i){
let img = new Image() // it will be destoryed every loop begin, even if use keyword 'var' insteads of 'let'.
img.onload = ()=>{
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0)
let imgData = ctx.getImageData(0, 0, 1024, 1024) // imgData will be all 0 or some other unexpected result.
}
img.src = urls[i]
}
// fixed bug
window.imgs = []
for(let i = 0; i < urls.length; ++i)
window.imgs[i] = new Image()
for(let i = 0; i < urls.length; ++i){
let img = window.imgs[i]
img.onload = ()=>{
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0)
let imgData = ctx.getImageData(0, 0, 1024, 1024)
}
img.src = urls[i]
}
The reason may be object reference, garbage collection and other problems. I don't know. Because I'm a beginner of js.

draw image to canvas proplem

its very confused i`m designing a 2d game and i use this code to draw images to canvas the alert method return background.x = 0 ! but when i change x to z or any letter its return the number 400 i ! why background.x always equal to zero ???
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
function loadResources(){
background = new Image();
background.src = "11.jpg";
background.width = 128;
background.height = 128;
background.x = 400;
background.y = 450;
}
function drawimage(){
alert(background.x);
context.drawImage(background,background.x,background.y,background.width,background.height);
}
function gameLoop() {
drawimage();
}
loadResources();
setInterval(gameLoop, 1000/60);
Unlike other objects, you are actually not able to set properties of an Image object that do not belong to it. As you've seen, when you try to access them after setting them, the properties will not be available. You can slightly rework your code as follows to get the behavior you're looking for:
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var resources = {};
function loadResources(){
resources.background = new Image();
resources.background.src = "11.jpg";
resources.background.width = 128;
resources.background.height = 128;
resources.backgroundx = 400;
resources.backgroundy = 450;
}
function drawimage(){
console.log(resources.backgroundx);
context.drawImage(resources.background,resources.backgroundx,resources.backgroundy,resources.background.width,resources.background.height);
}
function gameLoop() {
drawimage();
}
loadResources();
setInterval(gameLoop, 1000/60);

How to use canvas.toDataURL() to get base64 of image in Adobe AIR?

Is it possible to use canvas.toDataURL() in Adobe AIR?
When I try I get the following error:
Error: SECURITY_ERR: DOM Exception 18
Adobe AIR enforces same origin for images used in the canvas API. Once you've used something from another domain in your canvas, you can't get pixel data back out of it. However, you can make use of the Loader class to get the pixel data, and convert it into a canvas ImageData.
For example:
function getDataURL(url, callback) {
var loader = new air.Loader();
loader.contentLoaderInfo.addEventListener(air.Event.COMPLETE, function(event) {
var bitmapData = loader.content.bitmapData;
var canvas = document.createElement('canvas');
canvas.width = bitmapData.width;
canvas.height = bitmapData.height;
var context = canvas.getContext('2d');
var imageData = context.createImageData(canvas.width, canvas.height);
var dst = imageData.data;
var src = bitmapData.getPixels(bitmapData.rect);
src.position = 0;
var i = 0;
while (i < dst.length) {
var alpha = src.readUnsignedByte();
dst[i++] = src.readUnsignedByte();
dst[i++] = src.readUnsignedByte();
dst[i++] = src.readUnsignedByte();
dst[i++] = alpha;
}
context.putImageData(imageData, 0, 0);
callback(canvas.toDataURL());
});
loader.load(new air.URLRequest(url));
}
window.addEventListener('load', function() {
getDataURL('http://www.google.com/images/logo.gif', function(dataURL) {
air.trace(dataURL);
});
}, false);

Categories

Resources