Unable to draw image on canvas from image dataurl (Easeljs) - javascript

I am trying to draw an image on canvas from dataurl but nothing is showing up on the canvas. For testing purpose, I have two canvases. I am drawing an image using url on first canvas (which loads correctly) and then converting it into dataurl and drawing the dataurl in second canvas which fails to draw.
Below is my code:
test html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link href="bootstrap.min.css" rel="stylesheet">
<title>Something</title>
</head>
<body>
<div class="col-md-8" id="middle panel">
<div class="container-fluid">
<div class="row">
<canvas class="embed-responsive-item" id="docCanvas" height="800" width="1200"></canvas>
</div>
<!-- Middle Panel-Container-Row (Editor) -->
<div class="row">
<canvas class="embed-responsive-item" id="docCanvasNew" height="1000" width="1500"></canvas>
</div>
<!-- Middle Panel-Container-Row (Editor) -->
</div>
<!-- Middle Panel-Container -->
</div>
<div class="col-md-4" id="signWidget">
<p>Boot</p>
</div>
<br>
<!-- <canvas id="docCanvas" height="800" width="1200"></canvas> -->
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<script src="easeljs-NEXT.combined.js"></script>
<script src="bootstrap.min.js" type="text/javascript"></script>
<!-- <script src="signing.js"></script> -->
<script src="ease.js"></script>
</body>
test js
var canvas, stage;
var canvas_new, stage_new;
var offset;
var update = true;
var uri;
var uri_new;
$(function() {
function init() {
// create stage and point it to the canvas:
canvas = document.getElementById("docCanvas");
stage = new createjs.Stage(canvas);
canvas_new = document.getElementById("docCanvasNew");
stage_new = new createjs.Stage(canvas_new);
// enable touch interactions if supported on the current device:
createjs.Touch.enable(stage);
// enabled mouse over / out events
stage.enableMouseOver(10);
stage.mouseMoveOutside = true; // keep tracking the mouse even when it leaves the canvas
// load document image
var docImage = new Image();
docImage.src = "new_editor_filled.png";
docImage.onload = handleDocImageLoad;
}
init();
function stop() {
createjs.Ticker.removeEventListener("tick", tick);
}
function handleDocImageLoad(event) {
var image = event.target;
var bitmap;
var container = new createjs.Container();
stage.addChild(container);
bitmap = new createjs.Bitmap(image);
container.addChild(bitmap);
bitmap.x = 0 | 0;
bitmap.y = 0 | 0;
createjs.Ticker.addEventListener("tick", tick);
uri = canvas.toDataURL();
//uri_new = canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');
var docImageNew = new Image();
docImageNew.onload = handleDocImageLoadNew;
docImageNew.src = uri;
}
function handleDocImageLoadNew(event) {
var image = event.target;
var bitmap;
var container = new createjs.Container();
stage_new.addChild(container);
bitmap = new createjs.Bitmap(image);
container.addChild(bitmap);
bitmap.x = 100 | 0;
bitmap.y = 100 | 0;
stage_new.update();
//update = true;
//createjs.Ticker.addEventListener("tick", tick);
}
function tick(event) {
// this set makes it so the stage only re-renders when an event handler indicates a change has happened.
if (update) {
update = false; // only update once
stage.update(event);
}
}
});

Related

Adding and Removing Elements (Using Tickers)

I am having a hard time adding another object with tickers. I am trying to get eqn2 (i.e. 3+2=some input) to move down with the response() function. You can see in the response() function that the alert "New Question" is being called onto the screen correctly. The goal here is to have m=2 (it was at 1 before) so that the drop(2) gets called moving eqn2 down. I think the issue is that the ticker doesn't go back far enough to recognize obj[m].x = Math.random()*can.width that obj[m].y = 0.5. I don't know how to get it to work here, and any help would be much appreciated.
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="//code.createjs.com/createjs-2013.09.25.combined.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!----------------------------- Start Game ------------------->
<style>
#gameCanvas {
background-color: lightyellow;
}
</style>
<div class="canvasHolder1">
<div id="eqn1"> 3+3=<input type="text" id="q1j" />
</div>
<div id="eqn2"> 3+2=<input type="text" id="q2j" />
</div>
<button id="myBtn" onclick="response()">New Question</button>
<canvas id="gameCanvas" width="600" height="600">Not supported</canvas>
<script type="text/javascript">
var m=1;
function response(){
alert("New Question");
document.getElementById(`eqn${m}`).remove();
m=m+1;
stage.update();
}
const quest=[];
quest[m]= document.getElementById(`q${m}j`);
quest[m].addEventListener("keyup", function(event) {
if (event.keyCode === 13 ) {
document.getElementById("myBtn").click();
event.preventDefault();
}
});
const values = [];
values[m] = document.getElementById(`q${m}j`);
var stage = new createjs.Stage("gameCanvas");
var obj=[];
obj[m] = new createjs.DOMElement(document.getElementById(`eqn${m}`));
can = document.getElementById("gameCanvas");
obj[m].x = Math.random()*can.width;
obj[m].y = 0.5;
function startGame() {
stage.addChild(obj[m]);
createjs.Ticker.addEventListener("tick", handleTick);
createjs.Ticker.setFPS(1);
function handleTick(event){
drop(m);
stage.update();
}
}
function drop(i){
obj[i].x += 1;
obj[i].y +=3;
}
</script>
<body onload="startGame();">
<div >
<canvas>This browser or document mode doesn't support canvas object.</canvas>
</div>
</body>
</html>
This isn't really a ticker question. You have to redefine the variables you need in the response function before the ticker.
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="//code.createjs.com/createjs-2013.09.25.combined.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!----------------------------- Start Game ------------------->
<style>
#gameCanvas {
background-color: lightyellow;
}
</style>
<div class="canvasHolder1">
<div id="eqn1"> 3+3=<input type="text" id="q1j" />
</div>
<div id="eqn2"> 3+2=<input type="text" id="q2j" />
</div>
<div id="eqn3"> 5+2=<input type="text" id="q3j" />
</div>
<canvas id="gameCanvas" width="600" height="600">Not supported</canvas>
<script type="text/javascript">
var m=1;
var quest=[];
quest[m]= document.getElementById(`q${m}j`);
var values = [];
var stage = new createjs.Stage("gameCanvas");
var obj=[];
can = document.getElementById("gameCanvas");
function response(){
alert("New Question");
document.getElementById(`eqn${m}`).remove();
m=m+1;
quest[m] = document.getElementById(`q${m}j`);
quest[m].addEventListener("keyup", enterFunction);
values[m] = document.getElementById(`q${m}j`);
obj[m] = new createjs.DOMElement(document.getElementById(`eqn${m}`));
obj[m].x = Math.random()*can.width;
obj[m].y = 0.5;
stage.addChild(obj[m]);
}
function startGame() {
quest[m].addEventListener("keyup", enterFunction);
values[m] = document.getElementById(`q${m}j`);
obj[m] = new createjs.DOMElement(document.getElementById(`eqn${m}`));
obj[m].x = Math.random()*can.width;
obj[m].y = 0.5;
stage.addChild(obj[m]);
createjs.Ticker.addEventListener("tick", handleTick);
createjs.Ticker.setFPS(2);
function handleTick(event){
drop(m);
stage.update();
}
}
function drop(i){
obj[i].x += 1;
obj[i].y +=3;
}
function enterFunction(){
if (event.keyCode === 13 ) {
document.getElementById("myBtn").click();
}
}
</script>
<body onload="startGame();">
<div >
<canvas>This browser or document mode doesn't support canvas object.</canvas>
</div>
</body>
<button id="myBtn" onclick="response()">New Question</button>
</html>

Canvas drawImage() with image doesn't draw anything

I want to change all images src of document to dataURL.
I am trying to draw all image in canvas through for of loop but it doesn't work.
Help me!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<img src="./adudio1.png" alt=""height="300px"width="200px"class="i">
<img src="./adudio1.png" alt=""height="300px"width="500px"class="i">
</body>
<script>
const img = document.querySelectorAll("img");
for(items of img){
let c = document.createElement("canvas");
document.querySelector("body").append(c);
c.height=items.height;
c.width=items.width;
c.style="border:2px solid #CCC;";
ctx = c.getContext("2d");
ctx.drawImage(items,0,0)
}
</script>
</html>
Your code isn't waiting for the images to load. Add your canvas drawing code to the onload function of each image to execute it only once the image data arrives.
const images = document.querySelectorAll("img");
for (const image of images) {
image.onerror = function () {
console.error("image failed to load");
};
image.onload = function () {
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.height = image.height;
canvas.width = image.width;
canvas.style = "border: 2px solid #CCC;";
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
};
}
<img src="http://placekitten.com/200/300"
alt=""
height="300"
width="200"
class="i"
>
<img src="http://placekitten.com/200/300"
alt=""
height="300"
width="200"
class="i"
>
As an aside, height="300px"width="500px" needs spaces between properties and doesn't need px after each value.
Use const item rather than items to avoid creating a global in your loop.

Rotate image via Range Slider

Hi guys how to make the image rotate via range slider?
I built the function so it can range between 0 and 360 and show the value range, it's working fine, but how to apply this to rotate the image?
The crop image script documentation is here
I updated the code with the crop script, please help to rotate the image and output to a div
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Cropper.js</title>
<!-- <link rel="stylesheet" href="dist/cropper.css"> -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.css" />
<style>
.container {
max-width: 640px;
margin: 20px auto;
}
img {
max-width: 100%;
}
</style>
</head>
<body>
<div class="container">
<h1>Cropper with a range of aspect ratio</h1>
<div>
<img id="image" src="https://fengyuanchen.github.io/cropperjs/images/picture.jpg" alt="Picture">
</div>
<button onclick="cropper.getCroppedCanvas()">Save</button>
</div>
<!-- <script src="dist/cropper.js"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
var image = document.querySelector('#image');
var minAspectRatio = 1.0;
var maxAspectRatio = 1.0;
var cropper = new Cropper(image, {
ready: function () {
var cropper = this.cropper;
var containerData = cropper.getContainerData();
var cropBoxData = cropper.getCropBoxData();
var aspectRatio = cropBoxData.width / cropBoxData.height;
var newCropBoxWidth;
if (aspectRatio < minAspectRatio || aspectRatio > maxAspectRatio) {
newCropBoxWidth = cropBoxData.height * ((minAspectRatio + maxAspectRatio) / 2);
cropper.setCropBoxData({
left: (containerData.width - newCropBoxWidth) / 2,
width: newCropBoxWidth
});
}
},
cropmove: function () {
var cropper = this.cropper;
var cropBoxData = cropper.getCropBoxData();
var aspectRatio = cropBoxData.width / cropBoxData.height;
if (aspectRatio < minAspectRatio) {
cropper.setCropBoxData({
width: cropBoxData.height * minAspectRatio
});
} else if (aspectRatio > maxAspectRatio) {
cropper.setCropBoxData({
width: cropBoxData.height * maxAspectRatio
});
}
}
});
});
</script>
<script>
function updateTextInput(val) {
document.getElementById('textInput').value=val;
}
</script>
<input type="range" name="rangeInput" min="0" max="360" onchange="updateTextInput(this.value);">
<input type="text" id="textInput" value="">
<!-- FULL DOCUMENTATION ON https://github.com/fengyuanchen/cropperjs -->
</body>
</html>
You can use some javascript to set the rotation of the image when the slider value changes. Since you have jQuery:
$(function(){
let slider = $('input[type=range]'),
image = $('#image');
slider.on('change mousemove', function(){
image.css('transform', 'rotate(' + $(this).val() + 'deg)');
});
});
Side note: This type of event assignment - finding the element in javascript, rather than adding onchange attributes to the input - is much more flexible and maintainable.
Here's an example: https://codepen.io/benjamin-hull/pen/ewxboE
A couple of things to watch:
I've added the 'mousemove' event listener as well as 'change', so the user gets real-time feedback as they move the slider. This might be a problem, as mousemove can produce 100's of events. You might need to look at 'debouncing' that event to limit it to a sensible value.
In my example, I've set the slider to min -180, max 180 and a default of 0. This allows the user to rotate left and right.
You probably want the rotation to scale the image as well, so it always fills the frame.

javascript teechart curved line issue

I want to draw smoothed lines for chart.
I have already made a chart using teechart.js, but it is not good working.
I've attached an image. Left image is mine.
I'd like to make line such as right
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<title>Chart</title>
<script src="./js/three.min.js" type="text/javascript"></script>
<script src="./js/Detector.js" type="text/javascript"></script>
<script src="./js/TrackballControls.js" type="text/javascript"></script>
<script src="./js/helvetiker_regular.typeface.js"></script>
<script src="./js/teechart.js" type="text/javascript"></script>
<script src="./js/teechart-3d.js" type="text/javascript"></script>
<script type="text/javascript">
"use strict";
var three1, Chart1;
function draw() {
three1 = new Tee.Three("canvas1");
three1.setShowShadows(true);
Chart1 = new Tee.Chart(three1);
Chart1.addSeries(new Tee.Line([60,70,70,60,50,40,30,40,50,60,50,40] , 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')));
Chart1.addSeries(new Tee.Line([20,30,40,50,60,50,40,50,60,70,70,60]));
Chart1.title.text="";
Chart1.footer.text="";
Chart1.legend.visible = false;
Chart1.walls.back.size=0.2;
Chart1.walls.left.size=10;
Chart1.walls.bottom.size=10;
Chart1.walls.back.format.transparency=0.2;
Chart1.bounds.x = -100;
Chart1.bounds.y = 50;
Chart1.bounds.width = 900;
Chart1.bounds.height = 400;
Chart1.axes.left.setMinMax(0, 120);
if (three1.isEnabled()) {
Chart1.draw();
animate1();
} else {
// Show message (WebGL not available) :
Detector.addGetWebGLMessage();
// Disable WebGL and use HTML5 2D Canvas:
three1.setEnabled(false, Chart1);
}
// Loop
function animate1() {
three1.update();
requestAnimationFrame(animate1);
}
}
</script>
</head>
<body onload="draw()">
<canvas id="canvas1" style="width: 700px; height: 500px; display: inline; background: white;" width="800" height="500"></canvas>
</body>
</html>
Hope good answers.
Checking your code I see it misses a couple of details, but correcting them it works without problems:
Set smoothed lines. In your example it would be:
Chart1.series.items[0].smooth = 0.5;
Chart1.series.items[1].smooth = 0.5;
Include teechart-extras.js to define Tee.drawSpline. It would be something like this:
<script src="./js/teechart-extras.js" type="text/javascript"></script>
I think you should take a look at THREE.TubeGeometry where you can pass a spline/curve as a path for the tube:
extrudePath = // define some spline or curve;
segments = 64;
radius = 5;
radiusSegments = 8;
closed = false;
tube = new THREE.TubeGeometry( extrudePath, segments, radius, radiusSegments, closed );
mesh = new THREE.Mesh( tube, material );
scene.add( mesh );
Check also the examples here

HS Canvas image hover/swap

The idea of the project is to make a widget from this image, I know it's in B&W grey scale full. I have each image with the text in a separate image for example First green section of each of the sections (the blue outer ring is split into 5 images corresponding with the text)
I have made a canvas and set the images into separate divs so I can then add a hover effect which will allow me to change the image to the corresponding B&W image or a hover effect.
My issue is I cannot understand how to use an event such as onmouseover while in JS. Here is my code in full (I can use jQuery,bootstrap, anything).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PI Security Widget</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="css/styles.css?v=1.0">
<!--[if lt IE 9]>
<script src="js/jquery-1.12.0.min.js"></script>
<![endif]-->
<!--[JQuery]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<!--[JQuery]-->
<!--[CSS]-->
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<link href="css/effects.min.css" rel="stylesheet">
<!--[END CSS]-->
<!--[Bootstrap]>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<!--[Bootstrap]-->
</head>
<body>
<div id="header">
<h1>test</h1>
</div>
<!--<div class="hovereffect">-->
<!--<img class="img-responsive" src="images/b2.png" alt="">-->
<!--<div class="overlay">-->
<!--</div>-->
<!--</div>-->
<div id="container">
<h1>Test chart</h1>
<canvas id="myCanvas" width="700" height="700"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
</script>
<!--</div>-->
<div id="whitering">
<script>
var whitering = new Image();
whitering.onload = function() {
context.drawImage(whitering, 69, 50);
};
whitering.src = 'images/white.png';
</script>
</div>
<div id="b1">
<script>
var b1 = new Image();
b1.onload = function() {
context.drawImage(b1, 69, 50);
};
b1.src = 'images/b1.png';
</script>
</div>
<div id="b2">
<script>
var b2 = new Image();
b2.onload = function() {
context.drawImage(b2, 69, 50);
};
b2.src = 'images/b2.png';
</script>
</div>
<div id="b3">
<script>
var b3 = new Image();
b3.onload = function() {
context.drawImage(b3, 69, 50);
};
b3.src = 'images/b3.png';
</script>
</div>
<div id="b4">
<script>
var b4 = new Image();
b4.onload = function() {
context.drawImage(b4, 69, 50);
};
b4.src = 'images/bN.png';
</script>
</div>
<div id="b5">
<script>
var b5 = new Image();
b5.onload = function() {
context.drawImage(b5, 69, 50);
};
b5.src = 'images/bN.png';
</script>
</div>
<div id="greentab1">
<script>
var g1 = new Image();
g1.onload = function() {
context.drawImage(g1, 69, 50);
};
g1.src = 'images/g1.png';
</script>
</div>
<div id="greentab2">
<script>
var g2 = new Image();
g2.onload = function() {
context.drawImage(g2, 69, 50);
};
g2.src = 'images/g2.png';
</script>
</div>
<div id="greentab3">
<script>
var g3 = new Image();
g3.onload = function() {
context.drawImage(g3, 69, 50);
};
g3.src = 'images/g3.png';
</script>
</div>
<div id="greentab4">
<script>
var g4 = new Image();
g4.onload = function() {
context.drawImage(g4, 69, 50);
};
g4.src = 'images/g4.png';
</script>
</div>
<div id="greentab5">
<script>
var g5 = new Image();
g5.onload = function() {
context.drawImage(g5, 69, 50);
};
g5.src = 'images/g5.png';
</script>
</div>
<div id="greentab6">
<script>
var g6 = new Image();
g6.onload = function() {
context.drawImage(g6, 69, 50);
};
g6.src = 'images/g6.png';
</script>
</div>
<div id="yellowtab1">
<script>
var y1 = new Image();
y1.onload = function() {
context.drawImage(y1, 69, 50);
};
y1.src = 'images/y1.png';
</script>
</div>
<div class="yellowtab2">
<script>
var y2 = new Image();
y2.id="yellowtab2" ;
y2.onload = function() {
context.drawImage(y2, 69, 50);
};
y2.src = 'images/y2.png';
// function changeImage() {
// var image = document.getElementById('yellowtab2');
// if (image.src.match("y2")) {
// image.src = "images/y2.png";
// } else {
// image.src = "images/y2BW.png";
// }
// }
//
// y2.onload = function() {
// context.onmouseover(this.src = 'images/y2.png');
// };
//
// y2.onload = function() {
// context.onmouseout(this.src = 'images/y2BW.png');
// };
//
// $(document).ready(function(){
// $(".y2").hover(function() {
// $(this).attr("src","images/y2BW.png");
// }, function() {
// $(this).attr("src","images/y2.png");
// });
// });
</script>
</div>
</div>
<div id="footer">
<h1>sadasds </h1>
</div>
</body>
</html>
I understand that when you run the code the pictures won't show up, I have a zip file with all the separate pictures but I can't seem to upload it.
Any help on how to get this working would be much appreciated!
Your divs just have js in them to draw an image into the one canvas so... they don't really separate your images at all. Mouseovers on canvas I believe need to test for image bounds manually too i think.
What your trying to do seems better accomplished by using svg or even image maps since all the hoverable shapes are not square. If your graphic is an svg, you should be able to manipulate and do hovers on any part of it, if you go with old-school imagemaps you can just show separate hover png's absolutely positioned over the grey graphic, but will need your image map as a clear png positioned over all the other graphics.
SVG is the probably the best solution for irregular shapes. You can then just use css to change the color on parts of it.

Categories