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
}
}
Related
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();
}
});
I am using pdf.js to view the pdf, and adding canvas over the top of the each page to add image on click. Images are adding on mouse click but its not on exact position..
$('.page').on('click', function(e) {
console.log("fgdfgdfg")
console.log(e)
if($("#hotspotTool").hasClass('active')){
var pageIndex = window.PDFViewerApplication.pdfViewer.currentPageNumber;
var page = window.PDFViewerApplication.pdfViewer.getPageView(pageIndex);
if ($(e.target).parent().hasClass('page')) {
var pid = $(e.target).parent().attr("id");
console.log(pid)
var canvas=document.getElementById(pid).getElementsByClassName("annotationLayer_svg")[0]
console.log(canvas)
var canv_id = $(canvas).attr('id')
if(canvas){
count++
var ctx = canvas.getContext("2d");
base_image = new Image();
base_image.src = '/images/dot.png';
base_image.id="hotspot"+count
base_image.draggable="true"
console.log(base_image)
var x = e.offsetX - base_image.width/2,
y = e.offsetY - base_image.height/2;
console.log(x,y)
ctx.drawImage(base_image,x,y);
ctx.save();
$("#hotspotTool").removeClass("active");
$('#hotspotmodel').modal('show');
$('#submit').on('click', function() {
$(this).data('clicked', true);
$("#hotspotform").valid();
if( $("#hotspotform").valid()){
$('#hotspotmodel').modal('hide');
var page_value = document.getElementById("pagelink").value
var spot_link = window.location.href+"page="+page_value
var anchor = document.createElement("A");
anchor.appendChild(base_image)
anchor.setAttribute("href", spot_link);
}
});
}
}
}
})
How can I able to add image on mouse click on exact position
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);
I'm creating a audio player with visualizer.
But currently when I press the input to start the audio player my debug console returns:
Uncaught (in promise) DOMException: Failed to load because no
supported source was found.
What I'm currently doing is setting the whole audio element up in JS / jQuery:
var bins = 512;
var backgroundColour = "#2C2E3B";
var barColour = "#EC1A55";
var floorLevel = 32;
var audioContext;
var audioBuffer;
var audioAnalyserNode;
var initialized = false;
var songText = "";
var textSize;
var freqLookup = [];
var canvasContext;
var isStream = true;
var canvasWidth;
var canvasHeight;
var src;
var audioElement;
var isPlaying = false;
var volume = 1;
function play() {
audioElement = document.createElement('audio');
// Opus support check stuff
var streamEndpoint = 'http://**.**.**.**:8003/stream';
var canPlayOpus = (typeof audioElement.canPlayType === "function" && audioElement.canPlayType('audio/ogg; codecs="opus"') !== "");
if(volume > 1) {
volume = volume / 100;
}
audioElement.src = streamEndpoint;
audioElement.crossOrigin = 'anonymous';
audioElement.volume = volume;
audioElement.play();
isPlaying = true;
setUpCanvas(audioElement);
}
function pause() {
audioElement.pause();
audioElement.currentTime = 0;
audioElement.src = '';
isPlaying = false;
}
function setUpCanvas(audioElement){
try {
initCanvas(document.getElementById("canvas"));
if(typeof audioContext === 'undefined') {
audioContext = new AudioContext();
}
if (audioElement) {
isStream = true;
setupAudioApi(true, audioElement);
}
} catch(e) {
console.log(e);
}
}
function setupAudioApi(isStream, audioElement) {
//var src;
if (isStream){
if(typeof src === 'undefined'){
src = audioContext.createMediaElementSource(audioElement);
audioContext.crossOrigin = "anonymous";
audioAnalyserNode = audioContext.createAnalyser();
audioAnalyserNode.fftSize = bins * 4;
src.connect(audioAnalyserNode);
audioAnalyserNode.connect(audioContext.destination);
}
}
if (!isStream) {
src.start();
}
initialized = true;
initFreqLookupTable();
}
function initCanvas(canvasElement) {
canvasContext = canvasElement.getContext('2d');
canvasElement.width = canvasElement.clientWidth;
canvasElement.height = canvasElement.clientHeight;
canvasWidth = canvasElement.width;
canvasHeight = canvasElement.height;
requestAnimationFrame(paint);
}
function getFreqPoint(start, stop, n, binCount) {
return start * Math.pow(stop / start, n / (binCount - 1));
}
function initFreqLookupTable() {
var lastPoint = 0;
var bins = audioAnalyserNode.frequencyBinCount;
for(var i = 0; i < bins / 2; i++) {
//Scale to perceived frequency distribution
var newFreq = getFreqPoint(20, 20000, i * 2, bins);
var point = Math.floor(bins * newFreq / 20000);
while (point <= lastPoint) {
point++;
}
lastPoint = point;
freqLookup.push(point);
}
}
//Render some fancy bars
function paint() {
requestAnimationFrame(paint);
if(!initialized) {
alert('Er is iets fout gegaan');
return false;
}
canvasContext.clearRect(0, 0, canvasWidth, canvasHeight);
canvasContext.fillStyle = backgroundColour;
canvasContext.fillRect(0, 0, canvasWidth, canvasHeight);
var bins = audioAnalyserNode.frequencyBinCount;
var data = new Uint8Array(bins);
audioAnalyserNode.getByteFrequencyData(data);
canvasContext.fillStyle = barColour;
for(var i = 0; i < bins; i++) {
var point = freqLookup[i];
//Pretty much any volume will push it over 128 so we set that as the bottom threshold
//I suspect I should be doing a logarithmic space for the volume as well
var height = Math.max(0, (data[point] - floorLevel));
//Scale to the height of the bar
//Since we change the base level in the previous operations, 256 should be changed to 160 (i think) if we want it to go all the way to the top
height = (height / (256 - floorLevel)) * canvasHeight * 0.8;
var width = Math.ceil(canvasWidth / ((bins / 2) - 1));
canvasContext.fillRect(i * width, canvasHeight - height, width, height);
}
}
The stream is in audio/mpeg format, it does load when I simply create an audio element in HTML with a src.
Can someone help me clarify and find the solution to the DOMException I'm getting. I have been searching other cases of this error but the fixes there didn't resolve the problem.
Try creating the audio tag like this:
var audio = new Audio('audio_file.mp3');
And try setting the type:
audio.type = "audio/mpeg";
I think that will fix your problem.
This creates an element, identical to the one you use in your code.
I suggest you put an extension on your stream.
I know this way works, and I don't know why the other way doesn't.
I want to set a new position of body on BeginContact event but it's still not functional. It's writed in JavaSript with drawing to canvas but it doesn't matter for Box2d. In HTML file in body is only empty canvas, nothing else. Here is my code:
In the beginning of JS file are only declarated some variables.
Vec2 = Box2D.Common.Math.b2Vec2;
BodyDef = Box2D.Dynamics.b2BodyDef;
Body = Box2D.Dynamics.b2Body;
FixtureDef = Box2D.Dynamics.b2FixtureDef;
Fixture = Box2D.Dynamics.b2Fixture;
World = Box2D.Dynamics.b2World;
PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
DebugDraw = Box2D.Dynamics.b2DebugDraw;
var player;
It's followed by a setup function which is called in the beginning.
function setup()
{
canvas = document.getElementById("collisionCanvas");
context = canvas.getContext('2d');
document.getElementsByTagName('body')[0].style.backgroundColor = "black";
canvas.style.backgroundColor = "white";
canvas.width = 320;
canvas.height = 320;
world = new World(new Vec2(0, 10), false);
//Point of the problem!!!
//setting contact listener
var listener = new Box2D.Dynamics.b2ContactListener;
listener.BeginContact = function(contact)
{
var body1 = contact.GetFixtureA().GetBody();
var body2 = contact.GetFixtureB().GetBody();
if(body1.GetUserData().type == "player")
{
body1.SetPosition({x:5, y:5});
}
else
{
body2.SetPosition({x:5, y:5});
}
}
world.SetContactListener(listener);
var fixDef = new FixtureDef;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
var bodyDef = new BodyDef;
//creating ground
bodyDef.type = Body.b2_staticBody;
bodyDef.position.x = convertPixelsToMeters(160);
bodyDef.position.y = convertPixelsToMeters(320-32/2);
bodyDef.userData = {type: "static"};
fixDef.shape = new PolygonShape;
fixDef.shape.SetAsBox(convertPixelsToMeters(canvas.width/2), convertPixelsToMeters(32/2));
world.CreateBody(bodyDef).CreateFixture(fixDef);
//creating player
bodyDef.type = Body.b2_dynamicBody;
bodyDef.fixedRotation = true;
bodyDef.position.x = convertPixelsToMeters(160);
bodyDef.position.y = convertPixelsToMeters(160);
bodyDef.userData = {type: "player"};
fixDef.shape = new PolygonShape;
fixDef.shape.SetAsBox(convertPixelsToMeters(16), convertPixelsToMeters(16));
player = world.CreateBody(bodyDef);
player.CreateFixture(fixDef);
//setup debug draw
var debugDraw = new DebugDraw();
debugDraw.SetSprite(document.getElementById("collisionCanvas").getContext("2d"));
debugDraw.SetDrawScale(32.0);
debugDraw.SetFillAlpha(0.3);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(DebugDraw.e_shapeBit | DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);
window.setInterval(update, 1000 / 60);
}
And in the end are only update function, one helping function and that's it.
function update()
{
world.Step(
1 / 60 //frame-rate
, 10 //velocity iterations
, 10 //position iterations
);
world.DrawDebugData();
world.ClearForces();
}
function convertPixelsToMeters(x)
{
return x*0.03125;
}
$(function(){
setup();
})
Important is only the middle code where is BeginContact event where is calling the SetPosition function which doesn't work.
I tried change position in other places, for example on KeyDown event and there it was correct, so it's for me understandable why it doesn't work.
In the b2Contactlistner method we can not change any prperty or position.
You can take any boolean variable and make it true when in beign contact and if change the position of body according to boolean variable.
as in your code.......
var bodyyy;
var boolennn
listener.BeginContact = function(contact)
{
var body1 = contact.GetFixtureA().GetBody();
var body2 = contact.GetFixtureB().GetBody();
if(body1.GetUserData().type == "player")
{
//body1.SetPosition({x:5, y:5});
bodyyy = body1;
booleannn = true;
}
else
{
// body2.SetPosition({x:5, y:5});
bodyyy = body2;
boolennn = true;
}
}
Now In your Update method
if(booleann)
{
bodyyy.SetPosition({x:5, y:5})
}
SORRY I Donot know syntax of java script