EaselJS Picture scaling blurred out - javascript

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();
}
});

Related

How to make cursor shrink and grow?

I'm want to take image and insert it to cursor and on mouse scroll the cursor will shrink or grow.
I try to do it by convert image to base64 and then to cursor, i just test it without scroll and it always make black square cursor.
img64 = new Image();
img64.src = './assets/tools/pencil.png';
var cnva64 = document.createElement('canvas');
cnva64.height = img64.naturalHeight;
cnva64.width = img64.naturalWidth;
var ctx64 = cnva64.getContext('2d');
ctx64.drawImage(img64, 0, 0, cnva64.width, cnva64.height);
var base64String = cnva64.toDataURL();
Board.canvas.style.cursor = `url(${base64String}), auto`;
Edit
if i'm doing it like this it's work but it isn't take the size of it
img = new Image();
img.src = './assets/tools/cursor/pencil.png';
img.style.width = "58px";
img.style.height = "38px";
Board.canvas.style.cursor = `url(${img64.src}), auto`;
I manged to do what i wanted but then i notified by chrome
Remove cursors greater than 32x32 device-independent pixels intersecting native UI
window.addEventListener('load', () =>{
Board = new CanvasBoard()
Board.canvas.addEventListener('wheel', function(e) {
let linesize = document.getElementById("LineSizePicker");
let add = (e.deltaY/100)*-1
if(parseInt(linesize.value)+add<=88 && parseInt(linesize.value)+add>0){
linesize.value = parseInt(linesize.value)+add;
Board.ChangeLineSize(linesize.value);
}
});
})
class CanvasBoard{
constructor(){
this.canvas = document.querySelector("#canvas");
this.context = this.canvas.getContext("2d");
this.Mode = "Pencil";
let img = document.getElementById(`${this.Mode}IMG`)
let CursorBae64 = this.ToBase64(img,28)
this.canvas.style.cursor = `url(${CursorBae64}), auto`
}
ToBase64(img64,Size){
img64.Height = Size;
img64.width = Size;
let Canvas64 = document.createElement('canvas');
Canvas64.height = img64.Height;
Canvas64.width = img64.width;
let ctx64 = Canvas64.getContext('2d');
ctx64.drawImage(img64, 0, 0, Canvas64.width, Canvas64.height);
let Base64 = Canvas64.toDataURL();
return B64
}
ChangeLineSize(Size){
let img64 = document.getElementById(`${this.Mode}IMG`)
img64.src = document.getElementById(`Old${this.Mode}IMG`).src
if(Size>10 && Size<40){
let base64 = this.ToBase64(img64,Size);
img64.src = base64;
this.canvas.style.cursor = `url(${img64.src}) 0 -${Size}, auto`
}
this.lineThickness = Size
}
}

Why img.onload() function not working on ipad for exporting my chart data in pdf format?

I am trying to export my chart data consisting of image and data in a PDF. It works fine for me in laptop browser, but while I am trying to do the same in Ipad, the img.onload() function is not firing. I am not sure but I feel like it is due to the size of the image that is rendering in it. Can anybody help me with it? Can we change the pixels of the image that is being rendered?
The code is given below:-
function exportData(exportType) {
if (exportType) {
if (exportType == "pdf") {
alert("clicked pdf")
console.log("pdf export ....")
vm.toggleCanvas = !vm.toggleCanvas;
var canvas = "";
var ctxt = "";
// var img = "";
var sheets = "";
var svgURL = "";
canvas = document.getElementById('canvas');
$log.log($window.screen.width)
//resizing image for PDF
if ($window.screen.width >= 1500) {
canvas.width = $window.screen.width - 150;
} else {
canvas.width = $window.screen.width;
}
console.log("before canvas")
ctxt = canvas.getContext('2d');
sheets = document.styleSheets;
svgURL = generateSVGWithStyling('svg');
// var img = document.createElement('img');
var img = new Image();
console.log("after image")
console.log(img)
alert("imb")
img.src = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgURL);
img.onload = function () {
debugger
console.log("in load")
alert("in load")
ctxt.drawImage(this, 0, 0);
vm.cnvasImg = "";
vm.cnvasImg = canvas.toDataURL();
var content = "";
console.log("on load")
subExportData(vm.cnvasImg, exportType);
}
console.log(img.src)
} else {
vm.cnvasImg = "nothing";
subExportData(vm.cnvasImg, exportType);
}
}
}
Any help would be apprciated.
Can you please try with passing the width, height properties to Image constructor Object.
var img = new Image(Width, Height);

how reduce the memory usage of canvas in mobile browser

I'm trying to implement a feature in our project which will trigger the mobile camera when pressing a capture button from mobile browser, it will append the captured image as canvas to html page, but if we capture more than 2 image, the browser get's restart automatically and showing memory low warning. Please let me know is there any way to optimize the canvas size?.
Note:
I have tested only in mobile chrome.
I'm attaching the sample code below
html code:
<input type="file" id="camera" accept="image/*" capture>
<div id="MediaOutput"></div>
javascript:
var storedMediaList=[];
var mobile_picture = document.querySelector("#camera");
mobile_picture.onchange = function () {
var file = mobile_picture.files[0];
storedMediaList.push({id:(Math.floor(Math.random()*90000)+10000),data:file});
drawImage();
};
function drawImage()
{
$(".rc").remove().empty();
$("#MediaOutput").html("");
$("#MediaOutput").html("<div class='mediaWrapper'></div>");
storedMediaList.forEach(function(row,index,array)
{
$(".mediaWrapper").append("<div style='float:left;' class='ir' id='c"+row.id+"' class='pic'><div media-id="+row.id+" class='close-image' id='close-image' style='width:24px;background:url(images/close.png) no-repeat;height:25px;cursor:pointer;'></div><canvas id='cv"+row.id+"'></canvas> </div>");
var reader = new FileReader();
reader.onload = function (e) {
var dataURL = e.target.result,
c = document.querySelector("#cv"+row.id),
ctx = c.getContext('2d'),
img = new Image();
img.onload = function() {
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0, 0);
};
img.src = dataURL;
};
reader.readAsDataURL(row.data);
});
function resizeImage(img, percentage) {
var coeff = percentage/100,
width = $(img).width(),
height = $(img).height();
return {"width": width*coeff, "height": height*coeff}
}
$('.ir canvas').each(function(){
var newDimensions = resizeImage( this, 70);
this.style.width = newDimensions.width + "px";
this.style.height = newDimensions.height + "px";
});
var width = 0;
$('#MediaOutput .mediaWrapper div').each(function() {
width += $(this).outerWidth( true );
});
$('#MediaOutput .mediaWrapper').css('width', width + "px");
}
Thanks in Advance!!

Canvas to data url not working properly

I have a function that takes an img-element and returns a data url. This works like 7/10 times and returns a blank image 3/10 times. I view the created data url through my browser(chrome) and use the same images so I know that this function is returning broken images. Can anyone spot why?
function imgToDataURL(img) {
var canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var c = canvas.getContext('2d');
c.drawImage(img, 0, 0);
dataurl = canvas.toDataURL();
return dataurl;
}
$(function() {
img = new Image();
img.crossOrigin = '';
img.onload = function() {
newimg = new Image();
newimg.onload = function() {
document.body.appendChild(newimg);
}
newimg.src = imgToDataURL(img);
}
img.src = 'https://somedomain.s3.amazonaws.com/someimg.png';
});
This example works most of the time but sometimes ends with a large white rectangle instead of the image.
You have to wait for images to load before drawing them using .drawImage function.
Only after the image is loaded by the browser you can call your imgToDataURL function.
Something like this:
var image_sources = ["img1.png", "img2.png", "..."];
for(var i=0; i<image_sources.length; i++) {
var new_img = document.createElement("img");
new_img.onload = function() {
imgToDataURL(this);
};
new_img.src = image_sources[i];
}

How do I erase an image on html5 canvas

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.

Categories